Search code examples
vb.netalgorithmloopsfor-loopnested-loops

Generalizing increasing number of nested loop algorithm


Sorry for the terrible title, but I have no clue on how to generalize (or simplify) my loop case here.

I have a program that iterates to a sequence of integer, for example dimension=1 to 5. In each iteration, there will be a main loop, and inside the main loop, there will be a nested loop. The number of the nested loop will be [dimension]. For example, in dimension=1, there is a For loop. In dimension=2, there is a For loop inside a For loop. And so on.

Is there any possible way to simplify the algorithm? currently I'm manually write totally different code for each value of [dimension]. Imagine if dimension=1 to 100? I'll be dead.

Here's my piece of program (written in VB.NET)

for dimension=2

Dim result(2) As Integer
For i = 0 To 1
    For j = 0 To 1
        result(0)=i
        result(1)=j
    Next
Next

For dimension=3

 Dim result(3) As Integer
 For i = 0 To 1
     For j = 0 To 1
         For k = 0 To 1
             result(0)=i
             result(1)=j
             result(2)=k
         Next
     Next
 Next

For dimension=4

Dim result(4) As Integer
For i = 0 To 1
    For j = 0 To 1
        For k = 0 To 1
            For l = 0 To 1
                result(0)=i
                result(1)=j
                result(2)=k
                result(3)=l
            Next
        Next
   Next
Next

And so on..

Any suggestion? Thanks!


Solution

  • There are plenty of solutions:

    Recursion

    Idk, if vb.net supports methods, but if it does, this would probably be the simplest:

    void nestedLoop(int lower , int upper , int remaining_loops , int[] values)
        if(remaining_loops == 0)
            //process values list
        else
            for int i in [lower , upper)
                values[remaining_loops] = i
                nestedLoop(lower , upper , remaining_loops - 1)
    

    Integer Transformation

    In theory, a number can be represented by any radix:

    d_i * radix ^ i + d_i-1 * radix ^ (i - 1) ... + d_0 * radix ^ 0
    

    Consider each digit the value of one of the nested loops:

    for int i in [0 , max)
        for int j in [0 , max)
            for int k in [0 , max)
                ...
    

    Could be represented by a 3-digit number with radix max, where d_0 = i, d_1 = j, etc.. Basically how each digit is mapped to one of the values can be arbitrary and will only affect the order of the output.

    void nestedLoops(int upper , int dimension)
        for int i in [0 , pow(upper , dimension))
            int[] values
            int digit_sub = 1
    
            int tmp = i
            for int j in [0 , dimension)
                values[j] = tmp % dimension
                tmp /= dimension
    
            //all values of the loops are now in values
            //process them here
    

    There would be a few other options aswell, but these are the most common.