Skip to content

Instantly share code, notes, and snippets.

@pablo-meier
Created August 5, 2017 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pablo-meier/ebb98170d763a990612dbafb5011d492 to your computer and use it in GitHub Desktop.
Save pablo-meier/ebb98170d763a990612dbafb5011d492 to your computer and use it in GitHub Desktop.
JS powerset, got bored
function powerset(input) {
let accum = [];
// This loop which index in the array you begin pulling from
for (let start = 0; start < input.length; ++start) {
// This loop determines *how many* elements to add to your accumulator
for (let baseLength = 1; start + baseLength <= input.length; ++baseLength) {
const base = input.slice(start, start + baseLength);
accum.push(base);
}
}
accum.push([]);
return accum;
}
function run(input) {
console.log(`Powerset for ${JSON.stringify(input)} is ${JSON.stringify(powerset(input))}`);
}
const input1 = [1, 2, 3, 4, 5];
const input2 = [];
const input3 = [6, 6, 6];
const input4 = [7];
run(input1);
run(input2);
run(input3);
run(input4);
@pablo-meier
Copy link
Author

FWIW, it has bag semantics, so input3 will return many duplicate sets since it's all 6s.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment