C#中:N For循环 [英] C#: N For Loops

查看:181
本文介绍了C#中:N For循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何把这段代码转换有N个嵌套的for循环:

How would I convert this code to have n nested for loops:

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



所以,如果num是2,那么只会有2圈; i和j。

So if num is 2 then there would only be 2 for loops; i and j.

这是不是功课,我希望反复做。每个Console.WriteLine()需要被存储为喜欢的元素都在一起。

This is NOT homework and I was hoping to do it iteratively. Each Console.WriteLine() needs to be stored as like an element all together.

这节目的输出创建n维hyperspase指数。

The output of this programs creates n dimensional hyperspase exponents.

推荐答案

OK,你想的非递归的解决方案,它是的参数在NUM 的和的有嵌套循环不变号的,是吗?

OK, you want a nonrecursive solution which is parameterized in num and has a constant number of nested loops, yes?

下面是一条什么,一个方法的草图。填写详细信息是留给作为练习。

Here's a sketch of a method that does that. Filling out the details is left as an exercise.

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

First, I assume that you have an immutable type "Vector" which can be a 0-tuple, 1-tuple, 2-tuple, 3-tuple, ... n-tuple.

的方法,采用在矢量的大小,并返回该尺寸的向量序列

The method takes in the size of the vector and returns a sequence of vectors of that size.

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

有。这个问题已经被减少到两个较小的问题:

There. The problem has now been reduced to two smaller problems:

1)给定大小的num的载体,它是在序列中的最后一个载体

1) Given a vector of size num, is it the last vector in the sequence?

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

2) If not, what is the next vector?

这应该是很简单的工作什么的下一个向量给出电流之一:增加的最后时隙的值。如果这使得它太大,它设置到零,并增加前一时隙的值。重复,直到你发现,要增加的东西。

It should be quite straightforward to work out what the next vector is given the current one: increase the value of the last slot. If that makes it too big, set it to zero and increase the value of the previous slot. Repeat until you've found the thing that is to be increased.

请有意义吗?

这篇关于C#中:N For循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆