用c++编写一个程序来计算所有可能的方程

Create a program in C++ to calculate all possible equations

本文关键字:程序 计算所 有可能 方程 一个 c++      更新时间:2023-10-16

我的任务是编写一个c++程序来查找所有可能的带操作符的数学方程。下面是问题:

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

我需要一个想法如何开始与代码。是蛮力算法吗?我不知道如何交换运算符来创建可能的方程。我不是要求完整的解决方案,只是一个想法如何开始编码。

你可以这样想。+、-、*、/可分别视为1、2、3、4。现在,如果你要尝试所有不同的组合不管你得到的数字数组有多大,你可以这样看。的例子。4数字。

1,1,1,1  1,1,1,2  1,1,1,3  1,1,1,4
1,1,2,1  1,1,2,2  1,1,2,3  1,1,2,4

等等。希望这能有所帮助!

我想声明这不是我最初的想法。我将在下面添加参考。请在下面找到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

引用:

生成添加到目标(Java作业/面试)的所有数学表达式的组合

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.