通过用 JavaScript 填充缺失的运算符来完成等式

javascriptweb developmentfront end technologyobject oriented programming

我们需要编写一个 JavaScript 函数,该函数接收一堆数字并返回正确的运算顺序以满足等式。可以使用的运算符有 (+, −, *, /, ^, %)。

例如 −

输入:5 3 8 输出:5+3=8
输入:9 27 3 输出:9=27/3
输入:5 2 25 , 1 5 2 输出: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'
]

相关文章


有用资源