# Variable nr. of nested loops (playing with recursion)

So I’m not sure how useful this is (or if it even belongs in the “Gallery”). I feel I might have overcomplicated something. Maybe it’s a solution looking for a problem

First a simple version, with a factorial nr. of iterations for the inner loop:

Click to (un) expand
``````/** Nested loops using recursion

Each nested loop successively one less iteration than the "parent" loop, until 1 iteration.
Forwards nesting levels

2020.08.30 raron
*/

int nested = 4;
int loopCounter = 0;  // Innermost loop counter. Bsically factorial(!)

void setup()
{
println("Test");
println();
variableLoops(0);

println("nr. of innermost loops: " + loopCounter);
}

void draw()
{
exit();
}

void variableLoops(int looper)
{
if(looper == nested)
{
// innermost loop stuff here
loopCounter++;
return;
}
for(int tab=0; tab<looper; tab++) print("\t");
println("Level " + (looper) + " : ");
for(int i=0; i<nested-looper; i++)
{
for(int tab=0; tab<looper; tab++) print("\t");
println(" Count: " + i);
variableLoops(looper+1);
}
}
``````

And then a better version, with any number of iterations pr. nested loop:

Click to (un) expand
``````/** Nested loops using recursion

Any number of iterations in each nested loop.

2020.08.30 raron
*/

int [] loopLimit  = { 4, 2, 3 };          // loop array, counting from 0 to each element value-1
int nestedLoops   = loopLimit.length;     // nr. of nested loops
int [] loopIndex  = new int[nestedLoops]; // index counter of each loop

void setup()
{
for(int i=0; i<nestedLoops; i++) loopIndex[i] = 0;

variableLoops(0, loopLimit, loopIndex);

println(" Last count:");
println(loopIndex);

noLoop();
}

void draw()
{
exit();
}

void variableLoops(int nestedLoop, int[] loopLimit, int[] loopIndex )
{
if(nestedLoop == loopLimit.length)
{
// innermost loop stuff here
return;
}

for(int tab=0; tab<nestedLoop; tab++) print("\t");
println("Level: " + nestedLoop);
for(int i=0; i<loopLimit[nestedLoop]; i++)
{
loopIndex[nestedLoop] = i;
for(int tab=0; tab<nestedLoop; tab++) print("\t");
println(" Count: " + i);
variableLoops(nestedLoop+1, loopLimit, loopIndex);
}
}
``````
1 Like