获取多维数组的N个元素的所有组合 [英] Get all the combinations of N elements of multidimensional array

查看:462
本文介绍了获取多维数组的N个元素的所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to write an algorithm to get all the possible combinations of N elements inside a multi dimensional array of M elements.

类似于:

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

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

The number of elements inside the array may vary, the only thing set is the number of elements of the combinations.

顺序没关系,但你不能重复,我的意思是 [A,B] = = [B,A] ,所以第二个没有考虑。

The order doesn't matter but you cannot repeat, I mean ["A","B"] == ["B","A"], so the second one is not take in consideration.

任何帮助?

推荐答案

ChrisB解决方案有一个错误,他没有在arr.shift之前追逐循环的长度,它是没有返回最后一个组合,所以我认为这将完成这项工作:

ChrisB solution had a mistake, he wasn't chaching the length of the loop before the arr.shift, and it was not returning the last combination, so I think this will do the job:

function getCombinations(arr, n){
    var i,j,k,elem,l = arr.length,childperm,ret=[];
    if(n == 1){
        for(var i = 0; i < arr.length; i++){
            for(var 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;
    }
    i=j=k=elem=l=childperm=ret=[]=null;
}


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

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

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

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

这篇关于获取多维数组的N个元素的所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆