Skip to content

subsets

Subhajit Sahu edited this page Dec 28, 2022 · 5 revisions

List all possible subsets.

Similar: randomSubset, subsets, isSubset.


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

var x = [['a', 'b'], [1, 2]];
[...xilists.subsets(x)].map(a => [[...a[0]], [...a[1]]]);
// → [
// →   [ [], [] ],
// →   [ [ 'a' ], [ 1 ] ],
// →   [ [ 'b' ], [ 2 ] ],
// →   [ [ 'a', 'b' ], [ 1, 2 ] ]
// → ]

var x = [['a', 'b', 'c'], [1, 2, 3]];
[...xilists.subsets(x)].map(a => [[...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

Clone this wiki locally