我们需要编写一个JavaScript函数,该函数接受一堆数字并返回正确的操作序列以满足该方程式。可以使用的运算符为(+,-,*,/,^,%)。
例如-
Input : 5 3 8 Output : 5+3=8 Input : 9 27 3 Output : 9=27/3 Input : 5 2 25 , 1 5 2 Output : 5^2=25 , 1=5%2
对于每个输入,至少有一个可能的序列,我们需要返回至少一个正确的序列。
我们将用于解决此问题的算法是-
首先,我们在一侧选择较大的数字,例如1 4 7将为7
然后我们把等于等于面对中间。像1 4 7就是1 4 = 7
最后,我们求解方程
如果不行,我们尝试其他号码
为此的代码将是-
const arr = ["5 3 8", "9 27 3", "5 2 25", "1 5 2", "3 3 3 30"];
const findCombination = (arr = []) => {
const answers = [];
for(let i = 0; i < arr.length; i++){
const el = arr[i];
//使用蛮力尝试解决方案
for(let n = 0; n < 1000; n++){
const s = el.replace(/ /g, () => "+−
*/^%="[Math.floor(Math.random() * 7)]);
if(eval(s.replace(/=/g, "===").replace(/\^/g, "**")) === true
&& answers.indexOf(s) === −1){
answers.push(s);
};
};
}
return answers;
};
console.log(findCombination(arr));输出结果
控制台中的输出将是-
[ '5+3=8', '9=27/3', '5^2=25', '1=5%2', '3=3%3^30', '3^3+3=30', '3+3^3=30' ]