I'm trying to write a N number of nested loops with recursion, but it has taken me too long to achieve it. I haven´t resolved how to compare all the levels of the array which contains the index of the loops. My goal is to make the indexes array to walk through all the combinations.
For example, if N is 3 then the nested loops with iterations will look like:
var i = 10;
while (i--) {
var j = 10;
while (j--) {
var k = 10;
while (k--) {
if (i === 0 && j === 0 && k === 0) { return 0; }
}
}
}
and the combinations between i, j, k go from [9, 9, 9] to [0, 0, 0].
My attempt is this:
function nloops(n) {
loop(n, [], 0);
}
function loop(n, array, index) {
if(array.length != n) {
array[index] = 10 - 1;
loop(n, array, index + 1);
} else {
if ((n - index + 1) < 0) {
} else {
if (array[n - index + 1] > 0) {
array[n - index + 1]--; loop(n, array, index + 1);
}
}
}
}
nloops(3);
My expected behaviour would be the array to walk from [9, 9, 9] down to [0, 0, 0].