Skip to content

Instantly share code, notes, and snippets.

@christ776
Created April 18, 2019 15:01
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/db02774930308fce3e565531686f0e8d to your computer and use it in GitHub Desktop.
Save christ776/db02774930308fce3e565531686f0e8d 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"]);
/*
a bc
a cb
b ac
b ca
c ab
c ba
*/
function getPermutations (elements) {
if (elements.length === 1) {
return elements[0];
}
let permutations = [];
for (let i = 0; i < elements.length; i++) {
const firstChar = elements[i];
let elementsCopy = [...elements];
const x = elementsCopy.splice(i,1);
// console.log(x[0]);
// console.log(elementsCopy);
const subPermutations = getPermutations(elementsCopy);
for (var j = 0; j < subPermutations.length; j++) {
permutations.push(firstChar + subPermutations[j]);
}
}
return permutations;
}
// const result = getPermutations(["a","b","c","d"]);
const result2 = getPermutations([["1","3"], ["a"], ["4","5"]]);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment