【发布时间】:2012-07-04 18:40:02
【问题描述】:
我想从 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 x n] 数组(n 不需要固定)。非常感谢 VBA 的帮助。我对 C、Java 和 C# 很熟悉。 在此先感谢:)
编辑:
这与question asked here 不同。这不是笛卡尔积,其中 one 元素取自每个相关数组。我需要的输出没有这个限制;因此,这种情况下的组合数 > 链接问题中的组合数。 此外,第一列是内容的描述,必须伴随内容。
【问题讨论】:
-
也欢迎提供指向类似已回答问题的链接。
-
让
j从1开始而不是0不是有帮助吗? -
@Liam 编辑了为什么这不是重复的
标签: c# java vba combinations multidimensional-array