Skip to content

Instantly share code, notes, and snippets.

@jan-osch
Created June 22, 2018 09:31
Show Gist options
  • Save jan-osch/3b420750acbdb54f97406f342bfad6c1 to your computer and use it in GitHub Desktop.
Save jan-osch/3b420750acbdb54f97406f342bfad6c1 to your computer and use it in GitHub Desktop.
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])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment