Created
August 2, 2013 13:38
-
-
Save zacg/6139955 to your computer and use it in GitHub Desktop.
Function for generating binary combinations
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
//Returns an array of boolean values representing | |
//every possible combination of n binary digits | |
function binaryCombos(n){ | |
var result = []; | |
for(y=0; y<Math.pow(2,n); y++){ | |
var combo = []; | |
for(x=0; x<n; x++){ | |
//shift bit and and it with 1 | |
if((y >> x) & 1) | |
combo.push(true); | |
else | |
combo.push(false); | |
} | |
result.push(combo); | |
} | |
return result; | |
} | |
//Usage | |
combos = binaryCombos(3); | |
for(x=0; x<combos.length; x++){ | |
console.log(combos[x].join(',')); | |
} | |
//OUTPUT | |
//false,false,false | |
//true,false,false | |
//false,true,false | |
//true,true,false | |
//false,false,true | |
//true,false,true | |
//false,true,true | |
//true,true,true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment