Given a RPN stack as an array. That is, you will be given something like "2 3 4 + *", which represents "( 3 + 4 ) * 2" in what I'll call left-to-right notation (LTR). You are also given a hash; the key of each hash are operators as used the RPN system, the values are an array ref; each array is 2 elements long, the first being the priority of the operator, and the second indicating the associativity ( a op ( b op c ) == ( a op b ) op c defined associativity) of the operation (1 if associative, 0 if not). The hash (this will be given to you, and you should pass it to the sub) may be defined as such:
Operations with higher priority will be evaluated first in LTR notiation with the absence of parentheses for grouping. For example, " 3 + 4 * 5 " will do 4*5 before doing 3+(20) in this case. Operations of the same priority will be performed as they are encountered left to right (eg 3 + 4 - 5 would be (3+4)-5, or 2.) Anything in parentheses would be evaluated first.my %operations = ( '+' => [ 1, 1 ], '-' => [ 1, 0 ], '*' => [ 2, 1 ], '/' => [ 2, 0 ] );
Note that while typical arithmatic functions are used here, the sub should work with any %operations hash that's structured correctly.
Find the perl golf (minimum number of characters in the subroutine) solution that builds the LTR notation for the RPN stack. The solution should minimize the use of parentheses for grouping.
Some example cases, using the hash above, include:
"2 3 4 * 5 / +" --> 2 + 3 * 4 / 5 "3 4 * 5 / 2 +" --> 3 * 4 / 5 + 2 "3 4 5 / * 2 +" --> 3 * 4 / 5 + 2 "2 3 + 4 * 5 /" --> (2 + 3) * 4 / 5 "2 3 4 - -" --> 2 - (3 - 4) "2 3 - 4 -" --> (2 - 3) - 4 "2 3 4 + -" --> 2 - (3 + 4) "2 3 4 - +" --> 2 + 3 - 4
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: (Golf) Revisiting Reversing RPN Notation
by no_slogan (Deacon) on May 22, 2001 at 21:25 UTC |