0

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].

4
  • 1
    mywiki.wooledge.org/XyProblem What are you trying to achieve? Also, please use clear variable names. This is very hard to follow. Commented Jan 14, 2016 at 7:35
  • @MichaelDibbets I want to get all the combinations of the array, in this example the array will go from [9, 9, 9] to [0, 0, 0] passing through [9, 9, 8], [9, 9, 7], ..., [9, 8, 9], ..., [8, 8, 9], ..., etc. Commented Jan 14, 2016 at 7:43
  • yea, okay. But will there be only arrays in the arrays and an object of your choosing at the end you wish to do stuff with? or is it just to walk the combos? So is it [arr[arr[arr[object,object,object]]] or is it [arr[arr[object,arr[arr[object]]] Commented Jan 14, 2016 at 8:07
  • @MichaelDibbets I have read the link in your first comment and I think I know more what I want. I will make another question. Commented Jan 14, 2016 at 8:28

2 Answers 2

1

To use recursion properly, you need to switch from thinking about "how" to achieve the result to thinking about "what" the result is. For example, what is a combination of size n? If n is zero, the the result is an empty set, otherwise, it's a product of the source set and all combinations of size n - 1.

function combinations(elements, size) {
    var result = [];

    if (size === 0) {

        result.push([]);

    } else {

        combinations(elements, size - 1).forEach(function (previousComb) {
            elements.forEach(function (element) {
                result.push([element].concat(previousComb));
            });
        });
    }

    return result;
}

var combs = combinations(['a', 'b', 'c', 'd'], 3);
document.write("<pre>" + JSON.stringify(combs,0,3));

Sign up to request clarification or add additional context in comments.

Comments

0

You can always cheat a little: use a whole number and split and push it into an array on each iteration. Much easier than having to worry about what array index you need to update. Plus: bonus iterative function.

function pad(str) {
  if (str.length === 3) return str;
  return pad(0 + str);
}

function iter(n, init) {
  if (Array.isArray(n)) n = n.join('');
  var arr = pad(n.toString()).split('').map(Number);
  init.push(arr);
  return n === 0 ? init : iter(--n, init);
}

var out = iter([9, 9, 9], []);

DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.