C#/JS 获取二维数组组合
C#获取二维数组组合
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace HF.SHOP.WebSite { public partial class Demo : System.Web.UI.Page { List<List<string>> P_StringLL = new List<List<string>>(); List<string> P_tmpStrL = new List<string>(); protected void Page_Load(object sender, EventArgs e) { List<string> al = new List<string>(); al.Add("红色"); al.Add("黑色"); al.Add("紫色"); al.Add("白色"); P_StringLL.Add(al); al = new List<string>(); al.Add("小号"); al.Add("中号"); al.Add("大号"); al.Add("加大号"); P_StringLL.Add(al); al = new List<string>(); al.Add("男同志"); al.Add("女同志"); P_StringLL.Add(al); GroupArray("", P_StringLL, 0); StringBuilder sb = new StringBuilder(); foreach (string str in P_tmpStrL) { sb.AppendLine(str + "<br/>"); } Label1.Text = "总共有:" + P_tmpStrL.Count.ToString() + "种组合"; Label2.Text = sb.ToString(); } //组合计算 void GroupArray(string tmpStr, List<List<string>> strLL, int index) { int count = strLL.Count; if (count <= index) { if (tmpStr.Length > 0) { P_tmpStrL.Add(tmpStr); } return; } List<string> strL = strLL[index]; foreach (string str in strL) { GroupArray(tmpStr + str, strLL, index + 1); } } } }
JS代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Demo.aspx.cs" Inherits="HF.SHOP.WebSite.Demo" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <script src="UIResources/scripts/jquery.min.2.0.0.js"></script> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="Label1" runat="server" Text=""></asp:Label><br /> <asp:Label ID="Label2" runat="server" Text=""></asp:Label> <div id="cou"></div> <ul id="list"> </ul> </div> </form> <script type="text/javascript"> var array = [['红色', '黑色', '白色'], ['小号', '中号', '加大'], ['男', '女']]; var results = new Array(); //创建一个数组 var len = array.length; var indexs = {}; $(document).ready(function () { GetResults(-1); $("#cou").html("共有" + results.length + "种组合;<br/>"); for (var a = 0; a < results.length; a++) { $("#list").append("<li>" + results[a] + "</li>"); } }); function GetResults(start) { start++; if (start > len - 1) { return; } if (!indexs[start]) { indexs[start] = 0; } if (!(array[start] instanceof Array)) { array[start] = [array[start]]; } for (indexs[start] = 0; indexs[start] < array[start].length; indexs[start]++) { GetResults(start); if (start == len - 1) { var temp = []; for (var i = len - 1; i >= 0; i--) { if (!(array[start - i] instanceof Array)) { array[start - i] = [array[start - i]]; } temp.push(array[start - i][indexs[start - i]]); } results.push(temp); } } } </script> </body> </html>
作者:郑某人
出处:http://jsonzheng.cnblogs.com
欢迎转载或分享,但请务必声明文章出处。如果文章对您有帮助,希望你能推荐或关注。