I need an algorithm for evaluating postfix expression using recursion. In this postfix expression an operand can be of more than one digit. A space is used to distinguish between two operands. So an expression '45 68 +' is valid.
I thought of evaluating it in reverse direction but I think that should not be correct.
Can someone help me with just the algorithm.
Thanks in advance.
Doesn't strike me as a recursive-friendly problem. But I'm sure it could be done that way.
Two approaches occur to me:
Option #1: Make functional recursion calls and returns match the stack push and pop operations described on the Wiki.
Down side to this approach is that you'll quickly find that the returned data from the function can be fairly complex. It'll probably be an operator. Maybe with an optional operand (IE: number). You'll be returning structures/objects that maybe should have operations (methods) on them.
Option #2: Each recursive call processes the next character of the input stream.
I think this approach would pass in as parameters the stack and maybe an "accumulator" for the current number -- to accumulate digits into a number before pushing it on the stack. There would be one massive tail recursion numeric result returned.
This approach is really just rewriting a loop as recursion.
Either way, figuring it out yourself should be challenging and educational!
Following is a sort of pseudo code which will work for postfix expressions with +/- . I think you can further extend the idea. If you still face difficulty then mail me to 2shanks.p#gmail.com as I am not regular on this site.
void recursivePostfix(char* expr)
{
if(!expr) return;
bool flag=true;
static double result=0;
double v1=result, v2=0, dec=0;
char oper='0';
int i=0, state=1;
do
{
if('0' != oper)
{
switch(oper)
{
case '+': result=v1+v2; break;
case '-': result=v1-v2; break;
case '*': result=v1*v2; break;
case '/': result=v1/v2; break;
}
oper = '0';
v1 = result;
v2 = 0;
recursivePostfix(expr+i);
}
if(SPACE_CHAR == *(expr+i) && state++)
continue;
switch(state)
{
case 1:
v1 = v1*10 + (expr[i]-'0'); break;
case 2:
v2 = v2*10 + (expr[i]-'0'); break;
case 3:
oper = *(expr+i);
}
}while(0 != *(expr+i++));
cout << result;
}
I just code this for an interview, so here is my solution using Python:
def recursive_postfix(s):
s = s.split(' ')
if len(s) == 1:
return s[0]
res = None
for i in range(len(s)):
if s[i] in ['+', '-', '*', '/']:
res = eval(f'{s[i-2]}{s[i]}{s[i-1]}')
break
s = s[0:i-2] + [str(res)] + s[i+1:]
return recursive_postfix(' '.join(s))
assert recursive_postfix('2 2 + 1 *') == '4' # (2 + 2) * 1
assert recursive_postfix('3 4 2 + * 5 *') == '90' # 3 * (4 + 2) * 5
assert recursive_postfix('7 2 2 * -') == '3' # 7 - (2 * 2)
Related
im doing an assignment which requires me to create 3 classes.
1 with getting 2 random integers,
1 with getting random operators such as + - * / which should be done so in char method
the last one to check if the simple mathematics answer is correct using booleans via user Scanner input.
i need a little help here as im not sure if i've done the random operators method correctly and am really lost at how i should tabulate both random int and operators together in one class.
here's the code i've done so far:
public static char getOperator (int x, int y)
{
char operator;
int answer;
switch (rand.nextInt(4))
{
case 0: operator = '+';
answer = x + y;
break;
case 1: operator = '-';
answer = x - y;;
break;
case 2: operator = '*';
answer = x * y;;
break;
case 3: operator = '/';
answer = x / y;;
break;
default: operator = '?';
}
return operator;
}
I believe you mean you need to create 3 methods (and not classes).
One that creates a random integer (it's a bad design to create a
method that returns two integers instead of just calling two times
one that returns one int).
One that returns a random operator
One that checks if an operation consisting of "random-number
random-operator random-number" is equal to user input
Anyways, there's a lot to unpack here, so:
Your first method getTwoIntegers is incorrect, you're asking for two integers in input but you never actually use them, then you return one random number.
The method getOperator needs to be redesigned to have no input and return one char (equal to + - x /).
Your final method will call the your first method twice, then the second method once, it will then print the operation for the user to see, and check if the response is correct.
Hopefully this can help you conceptualize better the way you should build your code.
I didn't post the source code since I believe it's much better for you if you try to do it by yourself (this being an assignment and all)
Good luck and have fun :)
I am using Stack class to calculate simple arithmetic expressions involving integers,
such as 1+2*3.your program would execute operations in the order given,without regarding to the precedence of operators.
*Thus, the expression 1+2*3 should be calculated (1+2)*3=9,not 1+(2*3)=7.
If i get the input as 1+2*3,i know how to convert the string 1,2,3 to Integer.but i don't know how to covert +,* from string type to operator.
My code logic is:
For eg: Given string 2 + (3 * 5), So 3 * 5 will be operated first then +2 will be performed in result of 3 * 5.
probably the best way to do it will be equals, but it's best to ignore whitespaces:
i'm not quite sure how you split your string, but for example, if you have a char op and two integer a and b:
String str = op.replace(" ", "");
if(str.equals("*")){
retVal = a*b;
} else if(str.equals("+")){
retVal = a+b;
}//etc
Do what Ogen suggested and manually check the operator. A quick shortcut to doing the if, else if .... structure is switch, that is
switch(operand) {
case "*":
break;
case "+":
break;
.....
default:
}
You will have to manually check and assign the operator. E.g.
if (s.equals("+")) {
// addition
}
Quick solution: Use below code for executing correct javascript Arithmetic expression in java.
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine se = manager.getEngineByName("JavaScript");
try {
Object result = se.eval(val);
System.out.println(result.toString());
} catch (ScriptException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Ok, assuming your assignment needs you to use the Stack class and you already have the logic to pick numbers ( including the negative numbers -- that would an operator followed by another operator in all but one cases) and operators and parens, what you could do is as follows.
If you encounter a number, pop the last two elements from your stack. The first item you pop will be an operator and the next will be a number. Evaluate the expression and push it into Stack and continue.
You can ignore the parenthesis. You will also have to handle the case of reading a number or parenthesis the first time.
Just to be clear, this is not a homework assignment, I study CS in my own time!
I recently purchased a book entitled '50 puzzles for logical thinking' by Charles Phillips. I started one of them and it occurred to me that I could solve the problem using recursion. Here's the (paraphrased) question:
Insert a mathematical operator (+, -, ÷, x) in each of the spaces to solve the equation:
6 _ 3 _ 5 _ 7 _ 4 _ 8 = 13
It is my understanding, that in order to solve this problem using recursion, I first need to identify a base case. However, I'm having trouble doing this.
So my question is, what is a possible base case and how should I begin to implement it? What could the recursive function look like (arguments, return type etc)? (code is helpful please)!
This is what I have so far: Nearly working I think
See my answer for an implementation
N.b. I'm using Java
I think the stopping condition should mean that the equation is satisfied: all the operators filled in, and the operations resulting in a proper equality.
I would express the equation as a parse tree, with the leaves as numbers and the parents as operators. A tree naturally lends itself to recursion, because it's a hierarchical data structure.
Make an operator assumption where the root operation is the minus sign, the right child is the desired value (13), and the left child is the left hand side. Add an operator, evaluate the tree, and backtrack until your stopping condition is met.
The base case is when all the blanks are filled in with operators. You can solve this problem using depth-first backtracking search:
algorithm dfs(i):
if i == num_blanks: # base case: filled in all the blanks
if equation_solved():
return the operators you filled in
else:
for op in (+, -, ÷, ×):
blank[i] = op
if dfs(i + 1) returns a solution:
return that solution
blank[i] = _ # restore to previous state
This is a recursive way of searching through the entire combinatorial space. (I hope this doesn't spoil the exercise for you; I wrote it in pseudocode to leave the implementation to you.)
You can think of it as a tree of decisions.
6
/ / \ \
+ - * /
3 Assuming you choose + for the first operator
/ / \ \
+ - * /
5 5 5 5
^ ^
6 + 3 - 5 6 + 3 / 5
You can then use a graph traversal algorithm such as DFS or BFS to check the result. Both are naturally recursive.
Here is the implementation I ended up with, but first an explanation of the solution to the problem:
The base case (as said by larsmans and Jan Dvorak) is when all the "_" are filled with operators (such as "+").
The function calls itself, adding another parameter each time until it reaches a base case that is incorrect (e.g. "6+3+5+7+4-8=13") or it has a correct answer.
If the base case is incorrect, then we keep popping up levels we get to a level with an operator we can change.
Here's the code:
class GapFill {
private static String numbers; //E.g. 6_5_4=15
private static String[] blank; //Array of operators to go in the blanks
//Where:
//p = plus
//m = minus
//d = divide
//t = times
private static String[] operators = {"p", "m", "d,", "t"};
public static void main(String[] args) {
numbers = args[0];
blank = new String[numbers.split("_").length - 1];
if(dfs(0)) { //If a solution was found
int count = 0;
while(numbers.indexOf("_")!=-1) {
int index = numbers.indexOf("_");
numbers = numbers.substring(0,index)+blank[count]+numbers.substring(index+1);
count++;
}
System.out.println(numbers);
}
}
private static boolean dfs(int i) {
if(i == blank.length) { //base case: filled in all the blanks
return solveEquation();
}
for(String op : operators) {
blank[i] = op;
if(dfs(i + 1)) {
return true;
}
}
blank[i] = "_"; //restore to previous state
return false;
}
private static boolean solveEquation() {
String[] eachNumber = numbers.substring(0, numbers.indexOf("=")).split("_");
String finalResult = numbers.substring(numbers.indexOf("=")+1, numbers.length());
double currentResult = Double.parseDouble(eachNumber[0]);
for(int i=1;i<eachNumber.length;i++) {
String op = blank[i-1];
if(op==operators[0]) {
currentResult = currentResult + Integer.parseInt(eachNumber[i]);
} else if(op==operators[1]) {
currentResult = currentResult - Integer.parseInt(eachNumber[i]);
} else if(op==operators[2]) {
currentResult = currentResult / Integer.parseInt(eachNumber[i]);
} else if(op==operators[3]) {
currentResult = currentResult * Integer.parseInt(eachNumber[i]);
}
}
return (currentResult==Integer.parseInt(finalResult));
}
}
The output for java GapFill 6_3_5_7_4_8=13 is 6m3p5m7p4p8=13.
The "p,m,d,t" symbols are used instead of "+,-,÷,×" since the terminal doesn't like × or ÷
What I'm trying to do is read a line (string) and use it as a mathematical function to get (double) values or answers to it at different points (like a calculator basically)
I included a very simplistic code of what I'm trying to do just for the sake of being direct and straight forward:
double x, y, z;
String function;
x = 5;
y = 4;
function = "(x*y)+y";
z = Double.parseDouble(function);
/*
I want z to equal this
z = (x*y)+y;
*/
System.out.print("z= " + z);
Again, this is only a sample code to be clearer about my question. My question again is: how can I set z = function when z is a double and function is a string?
NOTE: I tried parse as you can see, but it didn't work. I also tried to read the string character by character, but it didn't work either because it added the value of the characters together.
I guess you are looking for a lexer and a parser.
These are basical components of every compiler or interpreter as
the lexer is able to split input (your string) into tokens
the parser is able to build a tree which represent the syntatic shape of your tokens to be furtherly interpretated semantically
This discipline is quite wide and I suggest you to start with something like ANTLR for Java, it is a parser generator that will generate both lexer and parser according to rules you specify through a grammar. There are many, this is just the first that came into my mind.
If you want to forget about all this theory just embed something like JavaScript or Groovy in your Java program, they are able to interpret code that is given at runtime so that you can just go that way.
Java does not have something like eval builtin. But you can use an expression language like spEL, mvel or Jexl for this.
Maybe this SO question can help you.
I suggest you have a look at Parboiled. Unlike nearly all other parser solutions for Java, you write your grammars... In Java.
What is more, among the Java examples, there are working calculators.
float eval(String exp)
{
char[] a = exp.toCharArray();
float[] buffer = new int[exp.length];
int k = 0;
for(int i : a)
{
if(a[i] >= 48 && a[i] <= 57) //checking for numbers
{
int x = a[i] - '0';
buffer[k++] = x;
}
else if(a[i] == '+' || a[i] == '-' || a[i] == '*' || a[i] == '/') //checking for operands
{
float result;
switch(a[i])
{
case '+': result = buffer[k] + buffer[k-1]; break;
case '-': result = buffer[k] - buffer[k-1]; break;
case '*': result = buffer[k] * buffer[k-1]; break;
case '/': result = buffer[k] / buffer[k-1]; break;
}
}
buffer[k++] = result;
}
return buffer[k]; //finally returning the recent value
}
Use a method like this. Will help a lot. Implemented using a stack data structure.
I have to write a program which reads in 3 numbers (using input boxes), and depending on their values it should write one of these messages:
All 3 numbers are odd
OR
All 3 numbers are even
OR
2 numbers are odd and 1 is even
OR
1 number is odd and 2 are even
This is what I have so far:
import javax.swing.JOptionPane;
class program3
{
public static void main(String[] args)
{
String num1 = JOptionPane.showInputDialog("Enter first number.");
String num2 = JOptionPane.showInputDialog("Enter second number.");
String num3 = JOptionPane.showInputDialog("Enter third number.");
boolean newnum1 = Integer.parseInt(num1);
boolean newnum2 = Integer.parseInt(num2);
boolean newnum3 = Integer.parseInt(num3);
}
}
This is where I am stuck. I am not sure how to use the MOD to display the messages. I think I have to also use an IF Statement too...But I'm not too sure.
Please help! :D
In Java, the modulus operator is %. You can use it like this:
if ( (a % 2) == 0) {
System.out.println("a is even");
}
else {
System.out.println("a is odd");
}
Combine it with some if statements or some counter to implement the final result.
PS: the type of newnumX looks odd :)
I would recommend you to
Start writing down in a piece of paper how would you do it manually.
( Write the algorithm )
Then identify which parts are "programmable" and which ones are not ( identify variables, statements, etc ) .
Try by hand different numbers and see if it is working.
From there we can help you to translate those thoughts into working code ( that's the easy part ).
These are basics programming skills that you have to master.
It is not worth we just answer:
boolean areAllEven = ( one % 2 == 0 ) && ( two % 2 == 0 ) && ( three % 2 == 0 ) ;
boolean areAllOdd = ( one % 2 != ..... etc etc
Because we would be diss-helping you.
Related entry: Process to pass from problem to code. How did you learn?
To avoid big ugly nested IFs, I would declare a small counter (in pseudocode):
if newnum1 mod 2 == 1 then oddcount += 1;
etc...
switch oddcount
case 0:
print "All three numbers are even"
etc...
Just a warning if you choose to use the % operator in Java: if its left-hand operand is negative, it will yield a negative number. (see the language specification) That is, (-5) % 2 produces the result -1.
You might want to consider bitwise operations e.g. "x & 1" to test for even/odd-ness.
Its even simpler than that, you have tree numbers a, b, c
n = a%2 + b%2 +c%2
switch (n):
case 0: 'three are even'
case 1: 'one is odd'
case 2: 'one is even'
case 3: 'three are odd'
And voila!
Write down the basic steps that you have to do to perform the task and then try to implement it in code.
Here is what you have to do:
1 - Get 3 numbers from the user.
2 - You need two variables: one to hold the number of odd inputs and the other to hold the number of the even ones. Lets call these evenCnt and oddCnt. (Hint: Since you know you only have 3 numbers, once you have determined one of these, the other one is just the difference from 3)
3 - Then you need a series of tests (If evenCnt is 3 then show "3 evens", else if ....)
(And Pascal and Kurosch have pretty much given you the fragments you need to fill in steps 2 and 3.)
[Edit: My #2 is wooly-headed. You only need one variable.]
Here you go. I just compiled and ran some test cases through this to confirm it works.
import javax.swing.JOptionPane;
class Program3 {
public static void main(String[] args) {
int evenCount = 0;
for (int i=0; i<3; i++) {
// get the input from the user as a String
String stringInput = JOptionPane.showInputDialog("Enter number " + (i+1) + ".");
// convert the string to an integer so we can check if it's even
int num = Integer.parseInt(stringInput);
// The number is considered even if after dividing by 2 the remainder is zero
if (num % 2 == 0) {
evenCount++;
}
}
switch (evenCount) {
case 3:
System.out.println("All are even");
break;
case 2:
System.out.println("Two are even, one is odd");
break;
case 1:
System.out.println("One is even, two are odd");
break;
case 0:
System.out.println("All are odd");
break;
}
}
}
BTW: I capitalized the class name because it's best practice to do so in Java.
I disagree with alphazero. I don't think two variables are REQUIRED. every number is either ever or odd. So keeping count of one is enough.
As for Asaph's code, I think it is well documented, but if you still want an explanation, here goes:
This is what the for loop does:
It reads (as Strings) user input for the 3 numbers
Integer.parseInt is a function that takes a String as a parameter (for example, '4') and returns an int (in this example, 4). He then checks if this integer is even by modding it by 2. The basic idea is: 4%2 = 0 and 9%2 = 1 (the mod operator when used as a%b gives the remainder after the operation a/b. Therefore if a%2 is 0, then a is even). There is a counter (called evenCount) that keeps track of how many integers are even (based on the %s test).
He then proceeds to do switch statement on the evenCount. A switch statement is sort of like an if-else statement. The way it works is by testing the switch parameter (in this case, evenCount) against the case values (in this case, 3, 2, 1, 0). If the test returns True, then the code in the case block is executed. If there is no break statement at the end of that case block, then, the code in the following case block is also executed.
Here, Asaph is checking to see how many numbers are even by comparing the evenCount to 0, 1, 2, and 3, and then usinga appropriate print statements to tell the user how many even numbers there are
Hope this helps