Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find all possible outcomes of a given expression in C++
Suppose we have an arithmetic expression without parentheses. Our task is to find all possible outcomes of that expression. Suppose the expression is like 1+2*3-4, this can be interpreted like below −
- 1+(2*(3-4)) = 1 + (2* -1) = -1
- (1+2)*(3-4) = 3 * -1 = -3
- 1+((2*3)-4) = 1 + (6 - 4) = 3
- ((1+2)*3)-4 = (3 * 3) - 4 = 5
- 1+(2*3)-4 = 1 + 6 – 4 = 3
To solve this problem, we have to follow these steps −
Initially set res as empty
-
For every operator x, do the following −
Recursively evaluate all possible values on left of x, let the list of values be L
Recursively evaluate all possible values on right of x, let the list of values be R
-
Loop through all values in L:
-
Loop through all values in R−
Apply current operator x on current element in L and R, and add the evaluated values to res
-
- return the res as output
Example
#include<iostream>
#include<vector>
using namespace std;
int solve(int a, char op, int b) {
if (op=='+')
return a+b;
if (op=='-')
return a-b;
if (op == '*')
return a*b;
}
vector<int> getAllResults(string expr, int low, int high) {
vector<int> res;
if (low == high) {
res.push_back(expr[low] - '0');
return res;
}
if (low == (high-2)) {
int num = solve(expr[low]-'0', expr[low+1], expr[low+2]-'0');
res.push_back(num);
return res;
}
for (int i=low+1; i<=high; i+=2) {
vector<int> L = evaluateAll(expr, low, i-1);
vector R = evaluateAll(expr, i+1, high);
for (int s1=0; s1<L.size(); s1++) {
for (int s2=0; s2<R.size(); s2++) {
int val = solve(L[s1], expr[i], R[s2]);
res.push_back(val);
}
}
}
return res;
}
int main() {
string expr = "1+2*3-4";
vector<int> ans = getAllResults(expr, 0, expr.length()-1);
for (int i=0; i< ans.size(); i++)
cout << ans[i] << endl;
}
Output
2 1 4 3 5 6 7 8
Advertisements