透過填充 JavaScript 中缺失的運算子來完成方程式


我們需要編寫一個 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];
      // using brute force to try solutions
      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'
]

更新於: 2020年11月21日

334 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.