javascript - 获取多维数组N个元素的所有组合

标签 javascript combinations

我正在尝试编写一个算法来获取 M 个元素的多维数组中 N 个元素的所有可能组合。

类似于:

function getCombinations(arr, n){
  ...
}

var arr = [ ["A"],["B","C"],["D","E"]];
var n = 2;

getCombinations(arr,n);

这应该产生:

[
["A","B"],["A","C"],["A","D"],["A","E"],
["B","D"],["B","E"],
["C","D"],["C","E"]
]

数组内元素的数量可能会有所不同,唯一设置的是组合的元素数量。

顺序并不重要,但不能重复,我的意思是 ["A","B"] == ["B","A"],所以第二个不是考虑在内。

有什么帮助吗?

最佳答案

ChrisB 解决方案有一个错误,他没有缓存 arr.shift 之前的循环长度,并且没有返回最后的组合,我认为这可以完成工作:

function getCombinations (arr, n) {
    var i, j, k, elem, l = arr.length, childperm, ret = [];
    if (n == 1){
        for (i = 0; i < arr.length; i++) {
            for (j = 0; j < arr[i].length; j++) {
                ret.push([arr[i][j]]);
            }
        }
        return ret;
    }
    else {
        for (i = 0; i < l; i++) {
            elem = arr.shift();
            for (j = 0; j < elem.length; j++) {
                childperm = getCombinations(arr.slice(), n-1);
                for (k = 0; k < childperm.length; k++) {
                    ret.push([elem[j]].concat(childperm[k]));
                }
            }
        }
        return ret;
    }
}


getCombinations([["A"],["B"],["C","D"]], 2);

// [["A", "B"], ["A", "C"], ["A", "D"], ["B", "C"], ["B", "D"]]

getCombinations([["A"],["B"],["C"],["D"]], 2);

// [["A", "B"], ["A", "C"], ["A", "D"], ["B", "C"], ["B", "D"], ["C", "D"]]

关于javascript - 获取多维数组N个元素的所有组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20052755/

相关文章:

r - 如何从 2 个或更多矩阵的所有可能组合创建矩阵?

c# - 如何使用字符串操作生成一整套组合?

javascript - 如何修复 table thead 和可滚动的 tbody(thead 包含 3 行)

javascript - 使用变量参数创建新的 Javascript 对象

javascript - 如果单击按钮,显示窗口确认并提交表单

android - 我如何使用领域知识来改进这个算法?呃,重量

javascript - 使用 jQuery 在 html 中嵌入 URL

javascript - 查看 Canvas 是否有任何数据(黑色除外)

javascript - 尝试返回递归组合函数而不得到 'undefined'

testing - 参数扫描 : rank parameters according to output