许多嵌套为循环

本文关键字:循环 嵌套 许多 | 更新日期: 2023-09-27 18:36:28

这个问题

在编码C#时遇到,但我认为答案适用于任何编程语言。

我需要多个嵌套循环(假设 9 个,但可以是 100 个)。我的代码应该像这样执行:

for (a1=0;a1<N;a1++)
for (a2=0;a2<N;a2++)
...
for (a9=0;a9<N;a9++)
   //do something

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

你能提供任何提示吗?

编辑:我知道我不需要使用嵌套循环来执行此操作。我只是问我是否可以使用变量M=9 int 数组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]]);

想象一下,使用更多数组:S4,S5,...第10节.(这可以是数组s[]数组,也可以是二维数组s[,]

许多嵌套为循环

limits 数组定义了每个组件的上限(-1,相当于 for 循环中的 <N)。组件数组保存每个组件的值。>

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

你的代码

for (a1=0;a1<N;a1++)
for (a2=0;a2<N;a2++)
...
for (a9=0;a9<N;a9++)

可以替换为:

    int M = 9;
    int N = 20;
    int index = 0;

    for (int x = 0; x < M; x++)
    {
        for (int y = 0; y < N; y++)
        {
            // do something
            // perhaps a[index++] = some value;
        }
    }

对于您的问题,有更好的解决方案,但我认为这是您所要求的。