我有五个不同长度的数组,我需要遍历所有数组以生成所有可能的内容组合。我目前正在使用 5 个嵌套的 for 循环,如下所示:
for (int a = 1; a < Array1.Length - 1; a++)
{
for (int b = 1; b < Array2.Length - 1; b++)
{
for (int c = 1; c < Array3.Length - 1; c++)
{
for (int d = 1; d < Array4.Length - 1; d++)
{
for (int e = 1; e < Array5.Length - 1; e++)
{
//do something
}
}
}
}
}
由于数组的大小,我最终进行了超过 4.56 亿次迭代。总的来说,我对编程很陌生,特别是 C#。我只是好奇是否有更有效的方法来完成此任务。
谢谢。
最佳答案
你经历了很多次迭代,因为有很多组合:这被称为 combinatorial explosion 。如果您必须尝试所有可能的组合,那么您就无法更有效地完成任务。
您可以通过使用递归以更少的代码行进行编码,或者无需对数组数量(在您的情况下为 5 个)进行硬编码。但是,迭代次数不会改变,只会改变代码行数。
void processCombination(int[] combination) {
// combination[i] has the index of array #i
...
}
void combine(int p, int[] indexes, int[] sizes) {
if (p == indexes.Length) {
processCombination(indexes);
} else {
for (indexes[p] = 0 ; indexes[p] != sizes[p] ; indexes[p]++) {
combine(p+1, indexes, sizes);
}
}
}
关于C# - 迭代多个数组/列表的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13655299/