Created
July 27, 2021 09:51
-
-
Save TuanMinPay/4e84e24862487df8b9d49b7e6e999d6b to your computer and use it in GitHub Desktop.
algorithm that calculates the result as the last number of the string
This file contains 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
let input = [1 , 1, 1, 1, 2]; | |
let permutations = [] | |
permutate([], { | |
pos1: ['+', '-', '*', '/', '='], | |
pos2: ['+', '-', '*', '/', '='], | |
pos3: ['+', '-', '*', '/', '='], | |
pos4: ['+', '-', '*', '/', '='] | |
}) | |
function permutate (currentVals, remainingAttrs) { | |
remainingAttrs[Object.keys(remainingAttrs)[0]].forEach(attrVal => { | |
let currentValsNew = currentVals.slice(0) | |
currentValsNew.push(attrVal) | |
if (Object.keys(remainingAttrs).length > 1) { | |
let remainingAttrsNew = JSON.parse(JSON.stringify(remainingAttrs)) | |
delete remainingAttrsNew[Object.keys(remainingAttrs)[0]] | |
permutate(currentValsNew, remainingAttrsNew) | |
} else { | |
permutations.push(currentValsNew) | |
} | |
}) | |
} | |
function check(input) { | |
var parts = input.split('='); | |
if (parts.length == 1) { | |
return false; | |
} | |
var ans = true; | |
var last = null; | |
for (var i in parts) { | |
var cur = eval(parts[i]); | |
if (last == null) { | |
last = cur; | |
} else { | |
ans = ans && (last === cur) | |
last = cur | |
} | |
} | |
return ans; | |
} | |
for (var i = 0; i < permutations.length; i ++) { | |
var curPerm = permutations[i]; | |
var newInput = input[0] + curPerm[0] + input[1] + curPerm[1] + input[2] + curPerm[2] + input[3] + curPerm[3] + input[4] | |
if (check(newInput)) { | |
console.log(newInput); | |
break; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment