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 this...
[1,2,3]
...how do I get this?
[
[1,2]
, [1,3]
, [2,3]
, [1,2,3]
]
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 this...
[1,2,3]
...how do I get this?
[
[1,2]
, [1,3]
, [2,3]
, [1,2,3]
]
After stealing this JavaScript combination generator, I added a parameter to supply the minimum length resulting in,
To use, supply an array, and the minimum subset length desired,
Output is,
I've modified the accepted solution a little bit to consider the empty set when min is equal to 0 (empty set is a subset of any given set).
Here is a full sample page to copy paste, ready to run with some output.
Combinations, short one:
And call as
If element order is important:
Then you may also want to consider a permutation.
BE WARNED !!! - Your machine can't handle arrays with >10 items.
Using binary numbers
This algorithm cries for recursion... this is how i would do it
Another fancy version of the above algorithm;
In order to understand whats going on lets go step by step
getSubArrays
function with the tail of the argument array. So tail of[1,2,3,4,5]
is[2,3,4,5]
.[5]
we return[[5]]
to the previousgetSubArrays
function call.getSubArrays
functionarr
is[4,5]
andsubarr
gets assigned to[[5]]
.[[5]].concat([[5]].map(e => e.concat(4), [[4]])
which is in fact[[5], [5,4], [4]]
to the to the previousgetSubArrays
function call.getSubArrays
functionarr
is[3,4,5]
andsubarr
gets assigned to[[5], [5,4], [4]]
.