Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const powerSet = (array) => {
- const results = [];
- const maximum = 1 << array.length;
- let reference = 0;
- while (reference < maximum) {
- results.push(array.filter((element, index) => reference & 1 << index));
- reference++;
- }
- return results;
- };
- const powerSetRecursive = ([first, ...rest]) => {
- if (rest.length === 0) {
- return [[], [first]];
- }
- const results = powerSetRecursive(rest);
- return results.concat(results.map(element => [first, ...element]));
- };
- const test = array => {
- const result = powerSet(array);
- const recursive = powerSetRecursive(array);
- console.log(result);
- console.log(recursive);
- console.log(result.length === 2 ** array.length);
- console.log(result.length === recursive.length);
- };
- test([1, 2, 3, 4, 5, 10])
Add Comment
Please, Sign In to add comment