2Darrays的所有可能组合

我想从2D [mxn]数组生成所有可能的组合,除了每个数组的第一个元素。 该元素代表表示其余元素的“类型”。 例如,如果我有一个数组

shirts[][] = { {"colour", "red", "blue", "green", "yellow"}, {"cloth", "cotton", "poly", "silk"}, {"type", "full", "half"} }; 

所需的输出应该是衬衫的所有可能性的组合。 对于上面的例子,

 colour red colour blue ... cloth silk type full type half colour red cloth cotton colour red cloth poly ... colour yellow type half cloth cotton type full ... cloth silk type half colour red cloth cotton type full ... colour yellow cloth silk type half 

我试过这样的事情(也得到了其他Stack Overflow 问题的帮助)

 String shirts[][] = { {"colour", "red", "blue", "green", "yellow"}, {"cloth", "cotton", "poly", "silk"}, {"type", "full", "half"} }; majorCombinations = new int[possibilities][shirts.length]; int currentCombination; int offset = 1; for (int i=0; i < shirts.length; i++) { currentCombination = 0; while (currentCombination < possibilities) { for (int j=0; j < shirts[i].length; j++) { for (int k=0; k < offset; k++) { if (currentCombination < possibilities) { majorCombinations[currentCombination][i] = shirts[i][j]; currentCombination++; } } } } offset *= shirts[i].length; } 

但它只给出了所有n个组合的值

 colour cloth type colour cloth full ... yellow silk half 

它没有考虑较小的组合,甚至不是通用的,即对于[mxn]arrays(n不需要修复)。 VBA的帮助将受到高度赞赏。 我也熟悉C,Java和C#。 提前致谢 :)

链接到原始答案

对于两个数组,两个嵌套循环应该:

 for (int i = 0 ; i != c[0].length ; i++) { for (int j = 0 ; j != c[1].length ; j++) { System.out.writeln(""+c[0][i]+c[1][j]); } } 

要获得更多嵌套,您需要一个递归或等效的基于堆栈的解决方案。

 void combos(int pos, char[][] c, String soFar) { if (pos == c.length) { System.out.writeln(soFar); return; } for (int i = 0 ; i != c[pos].length ; i++) { combos(pos+1, c, soFar + c[pos][i]); } } 

你想要的是笛卡尔积?

 var colours = new[]{"colour - red", "colour - blue", "colour - green", "colour - yellow"}; var cloth = new[] {"cloth - cotton", "cloth - poly", "cloth - silk"}; var type = new[]{"type - full", "type - half"}; var combinations = from c in colours from cl in cloth from t in type select new[]{c, cl, t}; 
 for (int i = 0; i < shirts[0].length; i++) { for (int j = 0; j < shirts[1].length; j++) { for (int k = 0; k < shirts[2].length; k++) { if (i != 0) System.out.print(shirts[0][0] + " " + shirts[0][i] + " "); if (j != 0) System.out.print(shirts[1][0] + " " + shirts[1][j] + " "); if (k != 0) System.out.print(shirts[2][0] + " " + shirts[2][k] + " "); System.out.println(); } } } }