C# - 最有效的方式来通过多个阵列/列表迭代 [英] C# - Most efficient way to iterate through multiple arrays/list
问题描述
我有长短不一的5个阵列,我需要通过所有这些生成的内容,所有可能的组合进行迭代。我目前使用嵌套像这样循环5:
I have five arrays of varying lengths and I need to iterate through all of them generating all possible combinations of the contents. I'm currently using 5 nested for loops like so:
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#具体。我只是好奇,如果有做到这一点更有效的方式。
Due to the size of the arrays, I end up with more than 456 million iterations. I'm pretty new to programming in general, and C# specifically. I'm just curious if there is a more efficient way to accomplish this.
感谢您。
推荐答案
您去,虽然有很多的迭代,因为有很多的组合:这就是所谓的的组合爆炸的。你不能做到这一点更有效,如果你必须通过所有可能的组合。
You go though that many iterations because there are that many combinations: this is called combinatorial explosion. You cannot do it more efficiently if you must go through all possible combinations.
您可以用更少的代码或不代码时硬编码阵列五个数(你的情况)使用的递归的。然而,迭代的数量不会改变,只有代码的行数
You can code it with fewer lines of code or without hard-coding the number of arrays (five in your case) by using recursion. However, the number of iterations is not going to change, only the number of lines of code.
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# - 最有效的方式来通过多个阵列/列表迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!