Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all possible subset combos in an array?

I need to get all possible subsets of an array with a minimum of 2 items and an unknown maximum. Anyone that can help me out a bit?

Say I have the following array:

[1, 2, 3] 

How do I get this?

[     [1, 2],     [1, 3],     [2, 3],     [1, 2, 3] ] 
like image 992
Stephen Belanger Avatar asked Apr 22 '11 03:04

Stephen Belanger


People also ask

How do you find all possible combinations?

To calculate combinations, we will use the formula nCr = n! / r! * (n - r)!, where n represents the total number of items, and r represents the number of items being chosen at a time. To calculate a combination, you will need to calculate a factorial.

How do you generate all possible subsets of a set in C++?

Find all distinct subsets of a given set in C++ So if the set is {1, 2, 3}, then the subsets will be {}, {1}, {2}, {3}, {1, 2}, {2, 3}, {1, 3}, {1, 2, 3}. The set of all subsets is called power set. The power set has 2n elements.


1 Answers

After stealing this JavaScript combination generator, I added a parameter to supply the minimum length resulting in,

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

To use, supply an array, and the minimum subset length desired,

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

Output is,

[[1, 2], [1, 3], [2, 3], [1, 2, 3]] 
like image 107
Anurag Avatar answered Sep 22 '22 04:09

Anurag