Skip to content

Instantly share code, notes, and snippets.

@zacg
Created August 2, 2013 13:38
Show Gist options
  • Save zacg/6139955 to your computer and use it in GitHub Desktop.
Save zacg/6139955 to your computer and use it in GitHub Desktop.
Function for generating binary combinations
//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