MathNV
MathNV

Reputation: 43

C# - Most efficient way to iterate through multiple arrays/list

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
                  }
              }
          }
      }
  }

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.

Thank you.

Upvotes: 2

Views: 3539

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

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);
        }
    }
}

Upvotes: 5

Related Questions