许多嵌套for循环

Tha*_*kis -2 c# for-loop

在编写C#时遇到了这个问题,但我认为答案适用于任何编程语言.

我需要多个嵌套循环(让我们说9,但可以是100).我的代码应该执行如下:

for (a1=0;a1<N;a1++)
for (a2=0;a2<N;a2++)
...
for (a9=0;a9<N;a9++)
   //do something
Run Code Online (Sandbox Code Playgroud)

我认为通过使用变量M=9和int数组a[]而不是a1,a2,a3,... 可以缩短此代码的速度.

你能提供任何提示吗?

编辑: 我知道我不需要使用嵌套循环来执行此操作.我只是问我是否可以使用变量M=9int数组a[]和更少的代码来做到这一点.

如果你真的需要看一些复杂的东西,我写了下面的代码:

        string[] s1 = new string[3]{ "apples", "oranges","bananas" };
        string[] s2 = new string[5] { "are", "are not", "should be", "must be","seem to be" };
        string[] s3 = new string[3] { "big", "small", "tasty" };

        int[] a=new int[10];
        int[] step = new int[10];
        step[1] = 1; step[2] = 1; step[3] = 2;
        for (a[1] = 0; a[1] < s1.Length; a[1]+=step[1])
            for (a[2] = 0; a[2] < s2.Length; a[2]+=step[2])
                for (a[3] = 0; a[3] < s3.Length; a[3]+=step[3])
                    Console.WriteLine(s1[a[1]] + " " + s2[a[2]] + " " + s3[a[3]]);
Run Code Online (Sandbox Code Playgroud)

想象一下有更多的数组:s4,s5,... s10.(这可以是数组数组s[],也可以是二维数组s[,].

Wey*_*ani 5

limits数组定义每个组件的上限(-1,相当于for循环中的<N).components数组包含每个组件的值.

int[] limits = { 9, 20, 15, 30, 8, 40, 10 };
int[] components = new int[limits.Length];

bool done = false;
while (!done)
{
    //do work here using the components
    int M = components[0];
    int N = components[1];
    int O = components[2];
    int P = components[3];
    //etc
    //first iteration M=0,N=0,O=0, etc

    //this part does the incrementing for the next iteration
    for (int j = 0; j < limits.Length; j++)
    {
        components[j]++;
        if (components[j] < limits[j])
            break;
        components[j] = 0;
        if (j == limits.Length - 1)
            done = true;
    }
}
Run Code Online (Sandbox Code Playgroud)