用C ++创建一个程序来计算所有可能的方程

时间:2016-06-28 16:19:58

标签: c++ algorithm brute-force

我有一个创建C ++程序的任务,用运算符查找所有可能的数学方程。下面显示了一个问题:

  

给出一组数字,例如{5,3,7,3和11}。使用+, - ,*,/等运算符找到所有可能的数学方程,使方程式产生给定的答案。例如,5 + 7-3 / 3 = 11。

我需要了解如何从代码开始。它是否像蛮力算法?我不知道如何交换运算符来创建可能的等式。我不是要求完整的解决方案,只是想知道如何开始编码。

2 个答案:

答案 0 :(得分:3)

你可以这样想。 +, - ,*,/可分别视为1,2,3,4。现在,如果你要尝试所有不同组合,无论你得到多少大小的数字,你都可以这样看待它。 例。 4个数字。

(defclass ROOM (is-a USER)
    (slot id
        (type SYMBOL))
    (slot windows-status
        (allowed-strings "open" "close")))

依此类推。希望这可能有所帮助!

答案 1 :(得分:3)

我想说这不是我最初的想法。我将在下面添加引用。请在下面找到C ++代码。它对你来说可能会有所帮助。

#include <iostream>
#include<string>
using namespace std;

void cntdwn(double sum, double previous, string digits, double target, std::string expr) {
   if (digits.length() == 0) {
     if (sum + previous == target) {
       std::cout<<expr << " = " << target;
     }
   } else {
     for (int i = 1; i <= digits.length(); i++) {
       double current = std::stod(digits.substr(0, i));
       string remaining = digits.substr(i);
       cntdwn(sum + previous, current, remaining, target, expr + " + " + std::to_string(current));
       cntdwn(sum, previous * current, remaining, target, expr + " * " + std::to_string(current));
       cntdwn(sum, previous / current, remaining, target, expr + " / " + std::to_string(current));
       cntdwn(sum + previous, -current, remaining, target, expr + " - " + std::to_string(current));
     }
   }
 }

 void f(string digits, double target) {
   for (int i = 1; i <= digits.length(); i++) {
     string current = digits.substr(0, i);
     cntdwn(0, std::stod(current), digits.substr(i), target, current);
   }
 }

int main() {
    // The digits go as concatenated string
    f("5373",11);
    return 0;
}

<强>输出

5 * 3.000000 - 7.000000 + 3.000000 = 11

<强>参考

Generate all combinations of mathematical expressions that add to target (Java homework/interview)

https://math.stackexchange.com/questions/459857/using-operators-and-4-4-4-4-digits-find-all-formulas-that-would-resolve

https://www.careercup.com/question?id=5735906000502784

附加说明

a) This code will not make any combinations for the digits. For example if we give (4,4,4,4) as numbers and 10 as target then it will not give any result as the solution in  that case should be [(44-4)/4] {this example has been picked from second reference].

b) And this problem is a classic algorithmic problme popularly known as "Countdown Problem" picked from famous UK game.