【问题标题】:When are the Combinations Being Appended/Pushed To the Array?何时将组合附加/推送到阵列?
【发布时间】:2017-12-01 01:54:52
【问题描述】:

我目前正在使用此代码来制作一个数组,其中包含数组中 10 个一组的数字的每种可能组合:

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);
}

例如,我的数字数组可能是[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],它会给我这些可能的组合:

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

我要做的只是将组合附加/推送/添加到我的数组,如果它们有一个特定的总数。我对javascript有点陌生,想知道是否有人可以告诉我在代码中的哪个位置确定组合并将其添加到我的数组(输出)中。

谢谢!

【问题讨论】:

  • 当initialStuff.length &gt;= size ...它就在(大概)你的代码中

标签: javascript arrays function combinations


【解决方案1】:

通过这些行将组合添加到结果中:

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

如果要添加其他条件,可以放在那里:

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

请注意,您不想将这两个测试合并到

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

这是因为循环和递归的 else 子句只应在长度测试失败时执行,它不应依赖于其他条件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-07
    • 2018-08-08
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-16
    • 2022-08-09
    相关资源
    最近更新 更多