Unlimited For loops

I want to run something like this:

For a = 0 To 4 For b = a To 4 For c = b To 4 Console.WriteLine(a & b & c) Next Next Next 

But I need to create n loops on top of each other. So I created this method:

 'iFrom = 0; iTo = 4; Depth = 3(loop count); Private Sub Iterate(ByVal iFrom As Integer, ByVal iTo As Integer, ByVal Depth As Integer) For i = iFrom To iTo If Depth - 1 > 0 Then Iterate(iFrom, iTo, Depth - 1) 'Do stuff here Next End Sub 

What would be the best way to get the "i" values ​​from higher levels? Should I store them in an array? Or is there a completely different way to approach this problem?

+7
source share
2 answers

After playing with this method, I finally found a solution. Here he is:

 Private Sub Iterate(ByVal iFrom As Integer, ByVal iTo As Integer, ByVal Depth As Integer, ByVal iValues As Integer()) For i = iFrom To iTo iValues(Depth - 1) = i If Depth - 1 > 0 Then Iterate(i, iTo, Depth - 1, iValues) Else 'Do stuff, in this case print the current iValues Console.WriteLine(String.Join("", iValues.Select(Function(x) x.ToString).ToArray)) End If Next Console.WriteLine() End Sub 'Usage: Dim iValueArray(Depth) As Integer Iterate(0, 1, 2, iValueArray) 
0
source

You can add an array or a similar structure with the Iterate() parameter and for each Iterate() call add the current value i to the array.

This way you can find out the depth of your loop and the current value of the "parent" loop.

0
source

All Articles