我想从2D [m x n]数组生成所有可能的组合,除了每个数组的第一个元素。该元素将代表表示其余元素的“类型”。例如,如果我有一个数组
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 Question获得帮助)
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
它没有考虑较小的组合,它甚至不是通用的,即对于[m×n]阵列(n不需要固定)。 VBA的帮助将受到高度赞赏。我对C,Java和C#很满意。 在此先感谢:)
修改
这与question asked here不同。这个不是笛卡尔积,其中一个元素取自所讨论的每个阵列。我要求的输出没有这个限制;因此,该场景中的组合数>链接问题中的组合数量。 此外,第一列是内容的描述符,必须伴随内容。
答案 0 :(得分:2)
对于两个数组,两个嵌套循环应该这样做:
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]);
}
}
答案 1 :(得分:0)
你想要的是笛卡尔积?
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};
答案 2 :(得分:0)
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();
}
}
}
}