On Nov 30, 2007 2:28 PM, Ruby Quiz <james / grayproductions.net> wrote:

> This week's quiz is to write a script that translates postfix expressions into
> the equivalent infix expression.  In the simplest form, your script should
> function as such:
>
>         $ ruby postfix_to_infix.rb '2 3 +'
>         2 + 3
>
> At minimum, try to support the four basic math operators:  +, -, *, and /.  Feel
> free to add others though.  For numbers, remember to accept decimal values.
> For an added bonus, try to keep the parentheses added to infix expressions to
> the minimum of what is needed.  For example, prefer these results:
>
>         $ ruby postfix_to_infix.rb '56 34 213.7 + * 678 -'
>         56 * (34 + 213.7) - 678
>         $ ruby postfix_to_infix.rb '1 56 35 + 16 9 - / +'
>         1 + (56 + 35) / (16 - 9)
>
> to these:
>
>         $ ruby postfix_to_infix.rb '56 34 213.7 + * 678 -'
>         ((56 * (34 + 213.7)) - 678)
>         $ ruby postfix_to_infix.rb '1 56 35 + 16 9 - / +'
>         (1 + ((56 + 35) / (16 - 9)))
>

Hi,

Fortunately, this week I had some time to check the Ruby quiz, and
even to code something. Unfortunately I only had about 10 minutes, so
I only solved the basic problem:

stack = []
expr = ARGV.join(" ")
expr.split(/ /).each do |x|
  case x
    when *%w{+ * - /}
      op2 = stack.pop
      op1 = stack.pop
      stack.push "(#{op1} #{x} #{op2})"
    else
      stack.push x
    end
  end
  puts stack.pop

This is how it works with the examples. It doesn't remove a single
parenthesis :-(

C:\Jesus>ruby quiz148.rb 2 3 +
(2 + 3)

C:\Jesus>ruby quiz148.rb "56 34 213.7 + * 678 -"
((56 * (34 + 213.7)) - 678)

C:\Jesus>ruby quiz148.rb 1 56 35 + 16 9 - / +
(1 + ((56 + 35) / (16 - 9)))

I'll try to find some time to implement some parenthesis
simplification, although I doubt I will succeed...

Thanks,

Jesus.