笛卡尔乘积是指在数学中,两个集合X和Y的笛卡尓积(Cartesian product),又称直积,表示为X × Y,第一个对象是X的成员而第二个对象是Y的所有可能有序对的其中一个成员 [1] 。
定义
X和
Y的笛卡尓积(Cartesian product),又称 直积,表示为
X×
Y,第一个对象是
X的成员而第二个对象是
Y的所有可能 有序对的其中一个成员
[3]
。
运算
案例
代码
C#源代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; public class Descartes { public static void run(List {
if (layer < dimvalue.Count - 1)
{
if (dimvalue[layer].Count == 0)
run(dimvalue, result, layer + 1, curstring);
else
{
for (int i = 0; i < dimvalue[layer].Count; i++)
{
StringBuilder s1 = new StringBuilder();
s1.Append(curstring);
s1.Append(dimvalue[layer][i]);
run(dimvalue, result, layer + 1, s1.ToString());
}
}
}
else if (layer == dimvalue.Count - 1)
{
if (dimvalue[layer].Count == 0) result.Add(curstring);
else
{
for (int i = 0; i < dimvalue[layer].Count; i++)
{
result.Add(curstring + dimvalue[layer][i]);
}
}
}
}
}
|
使用说明
,多个集合构成List
- > dimvalue作为输入
result之中作为输出
result = new List
();
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | import java.util.ArrayList; import java.util.List; //import com.alibaba.fastjson.JSON; public class DescartesUtil { public static void main(String[] args) { List new ArrayList Listnew ArrayList Listnew ArrayList Listnew ArrayList Listnew ArrayList listSub1.add("1"); listSub1.add("2"); listSub2.add("3"); listSub2.add("4"); listSub3.add("a"); listSub3.add("b"); listSub4.add("c"); listSub4.add("d"); list.add(listSub1); list.add(listSub2); list.add(listSub3); list.add(listSub4); List new ArrayList descartes(list, result, 0, new ArrayList // System.out.println(JSON.toJSONString(result)); } / * Created on 2014年4月27日 *
* Discription:笛卡尔乘积算法
* 把一个List{[1,2],[3,4],[a,b]}转化成List{[1,3,a],[1,3,b],[1,4
* ,a],[1,4,b],[2,3,a],[2,3,b],[2,4,a],[2,4,b]}数组输出
*
* * @param dimvalue原List * @param result通过乘积转化后的数组 * @param layer * 中间参数 * @param curList * 中间参数 */ private static void descartes(List List int layer, List if (layer < dimvalue.size() - 1) { if (dimvalue.get(layer).size() == 0) { DescartesUtil.descartes(dimvalue, result, layer + 1, curList); } else { for (int i = 0; i < dimvalue.get(layer).size(); i++) { Listnew ArrayList list.add(dimvalue.get(layer).get(i)); DescartesUtil.descartes(dimvalue, result, layer + 1, list); } } } else if (layer == dimvalue.size() - 1) { if (dimvalue.get(layer).size() == 0) { result.add(curList); } else { for (int i = 0; i < dimvalue.get(layer).size(); i++) { Listnew ArrayList list.add(dimvalue.get(layer).get(i)); result.add(list); } } } } } |
|
1
2
3
|
from itertools import product
for x,y,z in product(['a','b','c'],['d','e','f'],['m','n']):
print(x,y,z)
|
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/198582.html原文链接:https://javaforall.net

