Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: N For Loops

Tags:

c#

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

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

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.

The output of this programs creates n dimensional hyperspase exponents.

like image 697
Ames Avatar asked Jan 24 '10 23:01

Ames


1 Answers

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.

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) Given a vector of size num, is it the last vector in the sequence?

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.

Make sense?

like image 80
Eric Lippert Avatar answered Oct 12 '22 17:10

Eric Lippert