[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Fwd: Please Forward: Ruby Quiz Submission

James Gray

12/6/2007 12:27:00 PM

Begin forwarded message:

> From: "Aaron Suggs" <aaron@zenbe.com>
> Date: December 5, 2007 11:45:50 PM CST
> To: submission@rubyquiz.com
> Subject: Re: Please Forward: Ruby Quiz Submission
>
> It seems that people usually submit answers inline, rather than as
> attachments. Here's my solution inline, if that's more convenient than
> an attachment:
>
> # Ruby Quiz #148: Postfix to Infix
> # http://www.rubyquiz.com/qu...
> #
> # Solution by Aaron Suggs, aaron@zenbe.com
>
> # Some elementary arithmetic conventions
> ORDER_OF_OPERATORS = {
> '+' => 0,
> '-' => 0,
> '/' => 1,
> '*' => 1,
> '^' => 2, # Ooh, exponentiation
> '**' => 2
> }
>
> # Recursive infixer
> # Takes a stack (array), and order of its parent operator (Fixnum);
> # returns string of infix expression
> def r_infix(stack, parent_order)
> term = stack.pop
> if term =~ /\d/
> term.to_s
> else
> order = ORDER_OF_OPERATORS[term]
> # To preserve order of terms, compute right side before left
> right, left = r_infix(stack, order), r_infix(stack, order)
> str = "#{left} #{term} #{right}"
> order < parent_order ? "(#{str})" : str # add parens if needed
> end
> end
>
>
> begin
> # Get the postfix stack from ARGV
> stack = ARGV.first.split(/\s+/)
> # Converts postfix string to infix w/ minimal parentheses
> result = r_infix(stack, -1)
> raise("Stack not empty") unless stack.empty?
> puts result
> rescue
> puts "Malformed postfix expression"
> end
>
>
> Cheers,
> Aaron
>
> On Dec 6, 2007 12:24 AM, Aaron Suggs <aaron@zenbe.com> wrote:
>> Hi there,
>>
>> This is my first Ruby quiz submission. I'd appreciate it if you
>> forward it on to the list.
>>
>> Thanks for organizing these quizzes! They're a lot of fun.
>>
>> Cheers,
>> Aaron Suggs
>>