I'm trying to make a small program to solve the countdown problem. Basically, given a number n
and a vector of numbers, the problem outputs if n
can be constructed applying simple operations (say addition, div, mult, and subs).
The input I'm trying to give to the program is a string with reverse polish notation, so I made a small function to solve this kind of expressions.
Here is my code:
#include <iostream>
#include <stack>
#include <string>
#include <vector>
using namespace std;
bool is_number(const std::string& s) {
string::const_iterator it = s.begin();
while (it != s.end() && std::isdigit(*it)) ++it;
return !s.empty() && it == s.end();
}
vector<string> parseInput(const string& expression) {
vector<string> parsedInp;
string current = "";
for (auto token : expression) {
if (isdigit(token)) {
current += token;
}
else if (token == ' ') {
if (current != "") {
parsedInp.push_back(current);
current = "";
}
}
else {
parsedInp.push_back(string(1, token));
}
}
return parsedInp;
}
double operateExpression(const vector<string>& parsedInp) {
stack<double> expression;
for (auto token : parsedInp) {
if (is_number(token)) {
expression.push(stod(token));
}
else {
double op1 = expression.top();
expression.pop();
double op2 = expression.top();
expression.pop();
if (token == "+") {
expression.push(op1 + op2);
}
if (token == "-") {
expression.push(op1 - op2);
}
if (token == "*") {
expression.push(op1 * op2);
}
if (token == "/") {
expression.push(op1 / op2);
}
}
}
return expression.top();
}
vector<int> getSolution(vector<string> inp, const int target) {
vector<string> op = { "+", "-", "*", "/", "" };
//TODO....
}
int main() {
string expression;
getline(cin, expression);
vector<string> parsedInp = parseInput(expression);
cout << operateExpression(parsedInp) << endl;
}
So my first instinct was to create all possible permutations of the vector, and then try to concatenate the operations in the vector, but the problem that I'm facing now is that I can not find an easy way to do it. I can't concatenate it carelessly, because operateExpression
would fail, but I don't want to use try
and catch
for this problem. Also, I think there should be an easier way to do it.
So is there any better way to write getSolution
here? Thanks.
Aucun commentaire:
Enregistrer un commentaire