[如何在javascript中获取数组的每个唯一组合? [关闭]

问题描述 投票:-4回答:1

说我有数组:

[1, 2, 2, 3]

如何获得此数组的所有可能的唯一“拆分”,即:

[[1], [2, 2, 3]]
[[1], [2, 2], [3]]
[[1], [2, 3], [2]]
[[1], [2], [2], [3]]
[[1, 2], [2, 3]]
[[1, 2], [2], [3]]
[[1, 3], [2, 2]]
[[1, 3], [2], [2]]
[[1, 2, 2], [3]]
[[1, 2, 3], [2]]
[[1, 2, 2, 3]]

请注意,组合或组合内的顺序都不重要。即这些本质上是“多集”]

javascript arrays set theory
1个回答
0
投票

根据您的示例数组,只有15种组合。要获得所有可能的组合,可以使用此功能。

function subset(array){
   var subsets = [], tempArray;
   
   //loop throug possible combinations 
   for(var x = 1; x <= (Math.pow(2, array.length) - 1); x++) {
    tempArray = [];
    i = array.length;

    //loop through array 
    do {
        //using bitwise operator 
        //eg: x = 1, i = 1, condtion true store value
        if((x & (1 << i)) !== 0) {
          tempArray.push(array[i]);
        }
    } while(i--);

    subsets.push(tempArray);
     
   }
     
   return subsets; 
}


console.log(subset([1, 2]));
console.log(subset([1, 2, 2, 3]));
© www.soinside.com 2019 - 2024. All rights reserved.