max in reverse polish notation (RPN)

761 Views Asked by At

I am trying to implement max in my infixToPostfix generator. I did not ask this question on stackoverflow because it is more of a mathematical thing. I hope this is the right place.

$(1+2) / max(1,2,(3+4)/2)$ returns 1 2 + 1 2 3 4 + 2 / max /. This is right ouptput except I don't know how to solve the returned RPN. I mean RPN takes indefinite arguments. I thought of adding a suffix to max when converting from infix to postfix which indicates the number of arguments. I also thought of adding something like & or @ to tell that till here are the arguments. But I am looking for something universal. Are there any defined rules for RPN? If yes please provide with the answer the link to rules. I am also having problems implementing the unary $-$(negative). So if I could read the rules and implement it.

1

There are 1 best solutions below

2
On BEST ANSWER

The rule for calculating an expression in RPN is:

  • Make a stack of numbers
  • Process your RPN expression left-to-right
  • When you see a number, push it to the top of the stack
  • When you see a binary operator (e.g. +), apply that operator to the top-most two entries on the stack, pop those two entries and push the result.
  • When you see a unary operator, apply it to the top-most entry on the stack, pop that entry and push the result.
  • In general, if you see an $n$-ary operator, apply it to the top $n$ entries on the stack, pop those $n$ entries and push the result.

In the end, there will be only one number on the stack - the result.

As for unary minus, treat it as a unary operator, e.g.:

$$-(2-3)+5\to 23-_{binary}-_{unary}5+$$

As you see, you need to distinguish the binary minus from the unary minus.