Skip to content

Instantly share code, notes, and snippets.

@rd13
Created April 25, 2018 18:31
Show Gist options
  • Save rd13/917a4c7b297cf4a72dbdac00d5a01134 to your computer and use it in GitHub Desktop.
Save rd13/917a4c7b297cf4a72dbdac00d5a01134 to your computer and use it in GitHub Desktop.
Javascript cartesian product (power set) using bits
const input = 'abc'
const inputLength = 3
const powerSetSize = Math.pow(2, inputLength)
let result = []
for (let k = 0; k < powerSetSize; k++) {
let set = "";
let binaryDigits = k;
for (let j = 0; j < inputLength; j++) {
if (binaryDigits % 2 == 1) {
set += input.charAt(j);
}
binaryDigits >>= 1;
}
result[k] = set;
}
console.log(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment