Find Right Numbers Mix to reach target
by techsin
JavaScript
console.log(findCombos("123", 6));
function findCombos(num, target) {
var solutions = [];
var combos = getAllCombos(num);
var allVariations = tryAllMath(combos);
solutions = allVariations.filter(function(x){
return (evaluate(x.concat([])) == target);
});
return solutions.map(function(x){ return x.join(""); });
}
function tryAllMath(combos) {
var vrt = [];
var operators = ["*", "/", "-", "+"];
combos.forEach(function(combo) {
if (combo.length == 1) {
vrt.push(combo);
} else {
var ops = [];
for (var i = 0; i<combo.length-1; i++) ops.push(operators);
ops = allPossibleCases(ops);
ops.forEach(function(o){
var final = combo.slice();
var operators = o.split("");
operators.forEach(function(x,i){
final.splice(i*2+1,0,x);
});
vrt.push(final);
});
}
});
return vrt;
}
//http://stackoverflow.com/questions/4331092/finding-all-combinations-of-javascript-array-values
function allPossibleCases(arr) {
if (arr.length == 1) {
return arr[0];
} else {
var result = [];
var allCasesOfRest = allPossibleCases(arr.slice(1)); // recur with the rest of array
for (var i = 0; i < allCasesOfRest.length; i++) {
for (var j = 0; j < arr[0].length; j++) {
result.push(arr[0][j] + allCasesOfRest[i]);
}
}
return result;
}
}
function getAllCombos(str) {
var possible = [];
var C = Math.pow(2, str.length - 1);
for (var i = 0; i < C; i++) {
possible.push(binaryToSplit(str, i));
}
return possible;
}
function binaryToSplit(str, i) {
var len = str.length;
// get binary representation
var binaryStr = (i).toString(2);
for (var j = 0; j < len; j++) binaryStr = "0" + binaryStr;
binaryStr = binaryStr.substr(-len);
//get split on indexes of 1
var indexes = [];
for (var j = 0; j < len; j++)
if (binaryStr[j] == "1") indexes.push(j);
return splitAtIndexes(str, indexes);
}
function splitAtIndexes(str,...