简体   繁体   中英

When are the Combinations Being Appended/Pushed To the Array?

I am currently using this code to make an array of every combination possible of numbers in groups of 10 from an array:

var Util = function() {
};

Util.getCombinations = function(array, size, start, initialStuff, output) {
    if (initialStuff.length >= size) {
        output.push(initialStuff);
    } else {
        var i;
        for (i = start; i < array.length; ++i) {
            Util.getCombinations(array, size, i + 1, initialStuff.concat(array[i]), output);
        }
    }
}

Util.getAllPossibleCombinations = function(array, size, output) {
    Util.getCombinations(array, size, 0, [], output);
}

For example, my array of numbers could be [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] and it would give me these possible combinations:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 11]
[1, 2, 3, 4, 5, 6, 7, 8, 10, 11]
[1, 2, 3, 4, 5, 6, 7, 9, 10, 11]
[1, 2, 3, 4, 5, 6, 8, 9, 10, 11]
[1, 2, 3, 4, 5, 7, 8, 9, 10, 11]
[1, 2, 3, 4, 6, 7, 8, 9, 10, 11]
[1, 2, 3, 5, 6, 7, 8, 9, 10, 11]
[1, 2, 4, 5, 6, 7, 8, 9, 10, 11]
[1, 3, 4, 5, 6, 7, 8, 9, 10, 11]
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

What I'm trying to do is only append/push/add combinations to my array if they have a specific total. I'm somewhat new to javascript and am wondering if anyone could tell me where in the code the combination is determine and added to my array (output).

Thanks!

The combination is added to the result by these lines:

if (initialStuff.length >= size) {
    output.push(initialStuff);
}

If you want to add other criteria, you can put it there:

if (initialStuff.length >= size) {
    if (someOtherTest(initialStuff)) {
        output.push(initialStuff);
    }
}

Note that you don't want to combine the two tests into

if (initialStuff.length >= size && someOtherTest(initialStuff)) {
    output.push(initialStuff);
}

This is because the else clause, which loops and recurses, should only be executed when the length test fails, it shouldn't depend on the other criteria.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM