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 SubmissionIt 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
# Ruby Quiz - Postfix to Infix (#148)
#
# 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
endbegin
# 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"
endCheers,
AaronHi 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
ยทยทยท
Begin forwarded message:
On Dec 6, 2007 12:24 AM, Aaron Suggs <aaron@zenbe.com> wrote: