subsets - nodef/extra-lists GitHub Wiki

List all possible subsets.

Similar: randomSubset, subsets, isSubset.

function subsets(x, n)
// x: lists
// n: number of entries in each subset [-1 ⇒ any]
const xlists = require('extra-lists');

var x = ['a', 'b'], [1, 2](/nodef/extra-lists/wiki/'a',-'b'],-[1,-2);
[...xlists.subsets(x)].map(a => [...a[0](/nodef/extra-lists/wiki/...a[0), [...a[1]]]);
// → [
// →   [ [], [] ],
// →   [ [ 'a' ], [ 1 ] ],
// →   [ [ 'b' ], [ 2 ] ],
// →   [ [ 'a', 'b' ], [ 1, 2 ] ]
// → ]

var x = ['a', 'b', 'c'], [1, 2, 3](/nodef/extra-lists/wiki/'a',-'b',-'c'],-[1,-2,-3);
[...xlists.subsets(x)].map(a => [...a[0](/nodef/extra-lists/wiki/...a[0), [...a[1]]]);
// → [
// →   [ [], [] ],
// →   [ [ 'a' ], [ 1 ] ],
// →   [ [ 'b' ], [ 2 ] ],
// →   [ [ 'a', 'b' ], [ 1, 2 ] ],
// →   [ [ 'c' ], [ 3 ] ],
// →   [ [ 'a', 'c' ], [ 1, 3 ] ],
// →   [ [ 'b', 'c' ], [ 2, 3 ] ],
// →   [ [ 'a', 'b', 'c' ], [ 1, 2, 3 ] ]
// → ]

References