2016-06-28 31 views
1

我有一個任務來創建一個C++程序來查找運算符的所有可能的數學公式。下面顯示了這個問題:用C++創建一個程序來計算所有可能的方程

給定一組數字,例如{5,3,7,3和11}。用+, - ,*,/等運算符查找所有可能的數學公式,以便公式可以產生給定的答案。例如,5 + 7-3/3 = 11。

我需要一個想法如何開始與代碼。這是否像蠻力算法?我不知道如何交換操作員來創建可能的等式。我沒有要求完整的解決方案,只是一個想法如何開始編碼。

+0

蠻力是一種選擇,但你也可以保存結果是儘管向下票快 – Thomas

+0

,它看起來像一個有趣的問題,關於編程和數學。你可以嘗試用一個算法來解決這個問題,事實上,但你有很多代碼來寫可能的解決方案 – meJustAndrew

+0

我沒有看到圍繞暴力方法的方法。這是一個非常有趣的問題......這些數字的大小各不相同?該示例顯示了一個由5個數字組成的數組,但是可能會有更多或更少的數字? – 7Nate9

回答

3

你可以這樣想。 +, - ,*,/可以分別作爲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 

等等等等。希望這可能有幫助!

+0

但要小心*和/他們綁定超過+和 - – Thomas

+2

這是非常相關的算法的可能性數量,確實 – meJustAndrew

+0

感謝您的想法bro.But,首先如何互換運營商作爲你說兄弟?嵌套循環?我認爲一個壞主意。其次,如何存儲操作員bro。在數組中?作爲字符串?如果是這樣,而不是如何將字符串操作符更改回原始狀態,以便它可以執行操作? –

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. 
+0

非常感謝Rudrani的解釋。可以給我一些關於如何在括號中加入括號的想法嗎? –

+0

您可能想看看https://en.wikipedia.org/wiki/Operator-precedence_parser#Alternatives_to_Dijkstra.27s_Algorithm。底部有一個例子說明如何使一個方程式完全無效。 –

相關問題