Skip to content

Instantly share code, notes, and snippets.

@christ776
Created April 18, 2019 14:59
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 christ776/421e4ec50f6c4a8a4a428c31ba5f8a47 to your computer and use it in GitHub Desktop.
Save christ776/421e4ec50f6c4a8a4a428c31ba5f8a47 to your computer and use it in GitHub Desktop.
//You have an array of characters (string) that may be '1', '0' o '*'. e.g. 10*00*0. The program needs to
//generate an output of all the possible combinations by replacing * with an 0 and 1. I.e. input> 10**0
//output> 10000, 10010, 10100, 10110. Input > *0 output > 00, 10.
function findOcurrencesOf(character = "*", array) {
let occ = [];
for (let i = 0; i < array.length; i++) {
if (array[i] === character) {
occ.push(i);
}
}
return occ;
}
function produceCombinations(array) {
let occ = findOcurrencesOf("*", array);
console.log(occ)
let combos = binaryCombos(occ.length);
// Create a copy of the array
let result = [];
combos.forEach((combo, index) => {
let arrayCopy = [...array];
for (let i = 0; i < occ.length;i++) {
// console.log(combo);
arrayCopy[occ[i]] = combo.shift();
}
result.push(arrayCopy);
});
console.log(result);
}
//Returns an array of boolean values representing
//every possible combination of n binary digits
function binaryCombos(n){
let result = [];
for(let y=0; y<Math.pow(2,n); y++){
let combo = [];
for(x=0; x<n; x++){
//shift bit and and it with 1 so that basically we're moving a "1" from right to left
if((y >> x) & 1) {
combo.push("1");
}
else {
combo.push("0");
}
}
result.push(combo);
}
return result;
}
// Complexity is O(n!)
// Test Cases
produceCombinations(["1","0","*","*","0","*","0"]);
produceCombinations(["1","0","*","*","0"]);
produceCombinations(["*","0"]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment