C#:N For循环

Ame*_*mes 13 c#

我如何将此代码转换为n嵌套for循环:

            int num = 4;

            for (int i = 0; i <= num; i++)
            {
                for (int j = 0; j + i <= num; j++)
                {
                    for (int k = 0; i + j + k <= num; k++)
                    {
                        for (int l = 0; i + j + k + l <= num; l++)
                        {
                            Console.WriteLine(i + " " + j + " " + k + " " + l);
                        }
                    }
                }
            }
Run Code Online (Sandbox Code Playgroud)

因此,如果num为2,则只有2个for循环; 我和j.

这不是家庭作业,我希望迭代地做.每个Console.WriteLine()都需要像元素一样存储在一起.

该程序的输出创建了n维超高斯指数.

Eri*_*ert 14

好的,你想要一个非递归的解决方案,它在num中参数化并且具有恒定数量的嵌套循环,是吗?

这是一个方法的草图,这样做.填写细节留作练习.

首先,我假设你有一个不可变类型"Vector",它可以是0元组,1元组,2元组,3元组,...... n元组.

该方法获取向量的大小并返回该大小的向量序列.

IEnumerable<Vector> MakeVectors(int num)
{
    Vector current = new Vector(num); // make an all-zero vector with num items.
    while(true)
    {
        yield return current;
        Vector next;
        bool gotAnother = GetNextVector(current, out next);
        if (!gotAnother) break;
        current = next;
    }
}
Run Code Online (Sandbox Code Playgroud)

那里.问题现在已经减少到两个较小的问题:

1)给定一个大小为num的向量,它是序列中的最后一个向量吗?

2)如果没有,下一个向量是什么?

找出下一个向量给出当前向量的内容应该非常简单:增加最后一个槽的值.如果这样做太大,请将其设置为零并增加上一个插槽的值.重复,直到找到要增加的东西.

合理?


Meh*_*ari 11

通常,在具有嵌套循环的情况下,您将使用递归,其中嵌套循环的数量在编译时是未知的.有点想法的东西:

void func(const vector<int> &times, int depth) {
    if (depth == times.size()) return;
    for (int i = 0; i < times[depth]; ++i) {
        cout << depth;
        func(times, depth + 1);
    }
}
Run Code Online (Sandbox Code Playgroud)