找到阵列中所有可能的子集组合?

时间:2011-04-22 03:28:28

标签: javascript arrays subset

我需要获得一个阵列的所有可能子集,其中至少包含2个项目且未知最大值。有人可以帮我一点吗?

说我有这个......

[1,2,3]

......我怎么得到这个?

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

12 个答案:

答案 0 :(得分:56)

窃取this JavaScript组合生成器后,我添加了一个参数来提供最小长度,

var combine = function(a, min) {
    var fn = function(n, src, got, all) {
        if (n == 0) {
            if (got.length > 0) {
                all[all.length] = got;
            }
            return;
        }
        for (var j = 0; j < src.length; j++) {
            fn(n - 1, src.slice(j + 1), got.concat([src[j]]), all);
        }
        return;
    }
    var all = [];
    for (var i = min; i < a.length; i++) {
        fn(i, a, [], all);
    }
    all.push(a);
    return all;
}

使用,提供一个数组,以及所需的最小子集长度,

var subsets = combine([1, 2, 3], 2);

输出是,

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

答案 1 :(得分:12)

通过这个question的小调整,我希望我的解决方案更有效,因为它使用位运算符来生成所有子集。

var sets = (function(input, size) {
    var results = [], result, mask, i, total = Math.pow(2, input.length);
    for (mask = size; mask < total; mask++) {
        result = [];
        i = input.length - 1;

        do {
            if ((mask & (1 << i)) !== 0) {
                result.push(input[i]);
            }
        } while (i--);

        if (result.length >= size) {
            results.push(result);
        }
    }

    return results; 
})(['a','b','c','d','e','f'], 2);
console.log(sets);

答案 2 :(得分:8)

以下是使用ECMAScript 2015 generator function查找所有组合的方法:

&#13;
&#13;
function* generateCombinations(arr) {
  function* doGenerateCombinations(offset, combo) {
    yield combo;
    for (let i = offset; i < arr.length; i++) {
      yield* doGenerateCombinations(i + 1, combo.concat(arr[i]));
    }
  }
  yield* doGenerateCombinations(0, []);
}

for (let combo of generateCombinations([1, 2, 3, 4, 5])) {
  console.log(JSON.stringify(combo));
}
&#13;
&#13;
&#13;

要根据问题的要求限制到最小尺寸,只需确保组合的长度,然后再产生它:

&#13;
&#13;
function* generateCombinations(arr, minSize) {
  function* doGenerateCombinations(offset, combo) {
    if (combo.length >= minSize) {
      yield combo;
    }
    for (let i = offset; i < arr.length; i++) {
      yield* doGenerateCombinations(i + 1, combo.concat(arr[i]));
    }
  }
  yield* doGenerateCombinations(0, []);
}

for (let combo of generateCombinations([1, 2, 3, 4, 5], 2)) {
  console.log(JSON.stringify(combo));
}
&#13;
&#13;
&#13;

yield点限制允许以可读方式使此功能适应其他常见用例,例如,选择所有精确大小的组合:

&#13;
&#13;
function* generateCombinations(arr, size) {
  function* doGenerateCombinations(offset, combo) {
    if (combo.length == size) {
      yield combo;
    } else {
      for (let i = offset; i < arr.length; i++) {
        yield* doGenerateCombinations(i + 1, combo.concat(arr[i]));
      }
    }
  }
  yield* doGenerateCombinations(0, []);
}

for (let combo of generateCombinations([1, 2, 3, 4, 5], 2)) {
  console.log(JSON.stringify(combo));
}
&#13;
&#13;
&#13;

答案 3 :(得分:6)

这个算法要求递归...这就是我要做的事情

var arr = [1,2,3,4,5];
function getSubArrays(arr){
  if (arr.length === 1) return [arr];
  else {
  	subarr = getSubArrays(arr.slice(1));
  	return subarr.concat(subarr.map(e => e.concat(arr[0])), [[arr[0]]]);
  }
}
console.log(JSON.stringify(getSubArrays(arr)));

上述算法的另一个奇特版本;

var arr = [1,2,3,4,5],
    sas = ([n,...ns],sa) => !ns.length ? [[n]]
                                       : (sa = sas(ns),
                                          sa.concat(sa.map(e => e.concat(n)),[[n]]));

为了了解最新情况,请一步一步走

  • 直到最后我们得到一个长度为1的数组作为参数,我们继续使用参数数组的 tail 调用相同的getSubArrays函数。因此,[1,2,3,4,5]的尾部为[2,3,4,5]
  • 一旦我们将单个项目数组作为参数(例如[5]),我们就会将[[5]]返回到之前的getSubArrays函数调用。
  • 然后在之前的getSubArrays函数中arr [4,5]subarr被分配到[[5]]
  • 现在我们将[[5]].concat([[5]].map(e => e.concat(4), [[4]])实际上[[5], [5,4], [4]]返回到之前的getSubArrays函数调用。
  • 然后在之前的getSubArrays函数中arr [3,4,5]subarr被分配到[[5], [5,4], [4]]
  • 等......

答案 4 :(得分:5)

组合,短篇:

def test_filter_graded(self):
    eval1 = mock.MagicMock()
    eval2 = mock.MagicMock
    eval1.is_completely_graded.return_value = True
    eval2.is_completely_graded.return_value = False
    filter_graded([eval1, eval2])
    self.assertEqual(len(result), 1)

并致电

function combinations(array) {
    return new Array(1 << array.length).fill().map(
        (e1,i) => array.filter((e2, j) => i & 1 << j));
}

答案 5 :(得分:2)

使用二进制数

// eg. [2,4,5] ==> {[],[2],[4],[5],[2,4],[4,5],[2,5], [2,4,5]}

var a = [2, 4, 5], res = [];
for (var i = 0; i < Math.pow(2, a.length); i++) {
    var bin = (i).toString(2), set = [];
    bin = new Array((a.length-bin.length)+1).join("0")+bin;
    console.log(bin);
    for (var j = 0; j < bin.length; j++) {
        if (bin[j] === "1") {
            set.push(a[j]);
        }
    }
    res.push(set);
}
console.table(res);

答案 6 :(得分:1)

function combinations(array) {
  return new Array(1 << array.length).fill().map(
    (e1, i) => array.filter((e2, j) => i & 1 << j));
}

console.log(combinations([1, 2, 3]).filter(a => a.length >= 2))

你们能解释一下吗?

答案 7 :(得分:0)

我已经修改了接受的解决方案,以便在min等于0时考虑空集(空集是任何给定集的子集)。

这是一个完整的示例页面,用于复制粘贴,准备好运行一些输出。

<html>

<head>

<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>All Subsets</title>

<script type="text/javascript">

// get all possible subsets of an array with a minimum of X (min) items and an unknown maximum
var FindAllSubsets = function(a, min) {
    var fn = function(n, src, got, all) {
        if (n == 0) {
            if (got.length > 0) {
                all[all.length] = got;
            }
            return;
        }
        for (var j = 0; j < src.length; j++) {
            fn(n - 1, src.slice(j + 1), got.concat([src[j]]), all);
        }
        return;
    }
    var all = [];

    // empty set is a subset of the set (only when min number of elements can be 0)
    if(min == 0)
      all.push([-1]); // array with single element '-1' denotes empty set

    for (var i = min; i < a.length; i++) {
        fn(i, a, [], all);
    }

    all.push(a);
    return all;
}

function CreateInputList(){
  var inputArr = [];
  var inputArrSize = 4;
  var maxInputValue = 10;
  for(i=0; i < inputArrSize; i++){
    var elem = Math.floor(Math.random()*maxInputValue);
    // make sure to have unique elements in the array
    while(inputArr.contains(elem)){ // OR - while(inputArr.indexOf(elem) > -1){
      elem = Math.floor(Math.random()*maxInputValue);
    }
    inputArr.push(elem);
  }
  return inputArr;
}

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
}

function ArrayPrinter(arr){
  var csv = 'input = [';
  var i = 0;
  for(i; i<arr.length - 1; i++){
    csv += arr[i] + ', ';
  }
  csv += arr[i];

  var divResult = document.getElementById('divResult');
  divResult.innerHTML += csv + ']<br />';
}

// assumes inner array with single element being '-1' an empty set
function ArrayOfArraysPrinter(arr){
  var csv = 'subsets = ';
  var i = 0;
  for(i; i<arr.length; i++){
    csv += '[';
    var j = 0;
    var inArr = arr[i];
    for(j; j<inArr.length - 1; j++){
      csv += inArr[j] + ', ';
    }
    // array with single element '-1' denotes empty set
    csv += inArr[j] == -1 ? '&lt;E&gt;' : inArr[j];
    csv += ']';
    if(i < arr.length - 1)
      csv += '&nbsp;&nbsp;';
  }

  csv += ' &nbsp; (&#35; of subsets =' + arr.length + ')';

  var divResult = document.getElementById('divResult');
  divResult.innerHTML += csv + '<br />';
}

function Main(){
  // clear output
  document.getElementById('divResult').innerHTML = '';

  // sample run (min = 0)
  document.getElementById('divResult').innerHTML += '<hr/>MIN = 0 (must include empty set)<br />';
  var list = CreateInputList();
  ArrayPrinter(list);
  var subsets = FindAllSubsets(list, 0);
  ArrayOfArraysPrinter(subsets);
  document.getElementById('divResult').innerHTML += '<hr />';

  // sample run (min = 1)
  document.getElementById('divResult').innerHTML += 'MIN = 1<br />'; 
  var list = CreateInputList();
  ArrayPrinter(list);
  var subsets = FindAllSubsets(list, 1);
  ArrayOfArraysPrinter(subsets);
  document.getElementById('divResult').innerHTML += '<hr />';

  // sample run (min = 2)
  document.getElementById('divResult').innerHTML += 'MIN = 2<br />'; 
  var list = CreateInputList();
  ArrayPrinter(list);
  var subsets = FindAllSubsets(list, 2);
  ArrayOfArraysPrinter(subsets);
  document.getElementById('divResult').innerHTML += '<hr />';

  // sample run (min = 3)
  document.getElementById('divResult').innerHTML += 'MIN = 3<br />'; 
  var list = CreateInputList();
  ArrayPrinter(list);
  var subsets = FindAllSubsets(list, 3);
  ArrayOfArraysPrinter(subsets);
  document.getElementById('divResult').innerHTML += '<hr />';

  // sample run (min = 4)
  document.getElementById('divResult').innerHTML += 'MIN = 4<br />'; 
  var list = CreateInputList();
  ArrayPrinter(list);
  var subsets = FindAllSubsets(list, 4);
  ArrayOfArraysPrinter(subsets);
  document.getElementById('divResult').innerHTML += '<hr />';
}

</script>

</head>

<body>
  <input type="button" value="All Subsets" onclick="Main()" />
  <br />
  <br />
  <div id="divResult"></div>
</body>

</html>

答案 8 :(得分:0)

如果元素顺序很重要:

// same values, different order:

[1,2]
[2,1]

[1,3]
[3,1]

然后你可能还想考虑一种排列。

// ---------------------
// Permutation
// ---------------------
function permutate (src, minLen, maxLen){

    minLen = minLen-1 || 0;
    maxLen = maxLen || src.length+1;
    var Asource = src.slice(); // copy the original so we don't apply results to the original.

    var Aout = [];

    var minMax = function(arr){
        var len = arr.length;
        if(len > minLen && len <= maxLen){
            Aout.push(arr);
        }
    }

    var picker = function (arr, holder, collect) {
        if (holder.length) {
           collect.push(holder);
        }
        var len = arr.length;
        for (var i=0; i<len; i++) {
            var arrcopy = arr.slice();
            var elem = arrcopy.splice(i, 1);
            var result = holder.concat(elem);
            minMax(result);
            if (len) {
                picker(arrcopy, result, collect);
            } else {
                collect.push(result);
            }
        }   
    }

    picker(Asource, [], []);

    return Aout;

}

var combos = permutate(["a", "b", "c"], 2);


for(var i=0; i<combos.length; i++){
    var item = combos[i];
    console.log("combos[" + i + "]" + " = [" + item.toString() + "]");
}

警告!!! - 您的计算机无法处理包含&gt; 10项的数组。

  • 如果您的阵列有9个项目,则有近100万个组合。
  • 如果你的阵列有12个项目,则有超过10亿个组合。
  • 如果您的阵列有15个项目,则有超过3万亿个组合。
  • 如果您的阵列有18个项目,则超过17千万亿 组合。
  • 如果您的阵列有20个项目,则超过6个 quintillion组合。
  • 如果你的阵列有21个项目,那么结束了 138个sextillion组合。
  • 如果您的数组有22个项目,则有 超过3亿个组合。

答案 9 :(得分:0)

首次提交答案!希望它能帮助某人。我将此用于类似的递归解决方案,其中涉及到返回数组数组,我发现 flatMap() 方法非常有用。

var arr = [1,2,3,4,5];

function getAllCombos(arr){
   if(arr[0] === undefined) return [arr]
   return getAllCombos(arr.slice(1)).flatMap(el => [el.concat(arr[0]), el])
}
console.log(JSON.stringify(getAllCombos(arr)));

如果您希望console.log()输出以[1、2、3、4、5]而不是[5、4、3、2、1]开头,则可以添加sort()这样的混合方法:

var arr = [1,2,3,4,5];

function getAllCombos(arr){
   if(arr[0] === undefined) return [arr]
   return getAllCombos(arr.slice(1)).flatMap(el => [el.concat(arr[0]).sort(), el])
}
console.log(JSON.stringify(getAllCombos(arr)));

答案 10 :(得分:0)

这可能会也可能不会很好地进行基准测试,但这是另一种方式,而且非常简洁:

const combinations = arr => arr.reduce((acc, item) => {
  return acc.concat(acc.map(x => [...x, item]));
}, [[]]);


console.log(combinations([1, 2, 3]).filter(a => a.length > 1));

答案 11 :(得分:-1)

这里是C ++中的等效代码;

#include<iostream>
#include<math.h>
#include<vector>
using namespace std;

// Prints all Subset having min 2 elements
void printSubset(vector<int> subsetVect, int subsetElement) {

  if( subsetElement>= 2) {
    vector<int>::iterator itr;
    cout<<"\n[";
    for( itr = subsetVect.begin(); itr!=subsetVect.end(); itr++)
      cout<<*itr<<',';
    cout<<"]";   
  }
}
// Creates all possible subsets 
void allSubsets( int arr[], int n ) {

  /*set_size of power set(all possible subsets) of a set with set_size 
  n is ((2^n) -1)*/
  int pow_set_size = pow(2, n); 
  int counter, j;
  int subsetElement=0;
  /*Run from counter 000..0 to 111..1*/
  for( counter =0; counter< pow_set_size; counter++ ) {

    vector<int> subsetVect; 
    subsetElement = 0;
    for(  j=0; j<n; j++) {           
      /* Check if jth bit in the counter is set 
      If set then print jth element from set */ 
      if( counter & ( 1 << j )){
        subsetVect.push_back(arr[j]);
        subsetElement++;
      }
    }
    printSubset(subsetVect, subsetElement);
  }
}
int main(){
  int arr[]={1,2,3}, n=3;
  allSubsets(arr,n);// Ans. [1,2],[1,3],[2,3],[1,2,3] 
}