Created
August 5, 2017 15:24
-
-
Save pablo-meier/ebb98170d763a990612dbafb5011d492 to your computer and use it in GitHub Desktop.
JS powerset, got bored
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FWIW, it has bag semantics, so
input3
will return many duplicate sets since it's all 6s.