[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/5/2007 2:58:00 PM

Begin forwarded message:

> From: "Vasil Vangelovski" <vvangelovski@gmail.com>
> Date: December 5, 2007 7:55:12 AM CST
> To: submission@rubyquiz.com
> Subject: Please Forward: Ruby Quiz Submission
>
> #!/usr/bin/env ruby
> #
> # Created by Vasil Vangelovski on 2007-12-05.
> # Copyright (c) 2007. All rights reserved.
> #
> # Solution for ruby quiz 148
> # Thanx for posting something that can be solved on coffee-breaks
>
> class String
>
> #checks if the string is an operator
> def op?
> return (self=='+')||(self=='-')||(self=='*')||(self=='/');
> end
>
> #returns true only for strings that represent integer or decimal
> numbers
> def number?
> #there's a way to simplify this!!! (maybe later)
> int = false
> dec = false
> int = (/[0-9]+/.match(self)[0] == self) if !/
> [0-9]+/.match(self).nil?
> dec =(/[0-9]+[.]{0,1}[0-9]+/.match(self)[0] == self) if
> !/[0-9]+[.]{0,1}[0-9]+/.match(self).nil?
> return int||dec
> end
>
> end
>
> postfix_exp=ARGV[0]
> tokens = postfix_exp.split(' ')
>
> #the postfix->infix algo goes like this
> stack = []
> tokens.each {|token|
> if token.number?
> stack.push(token)
> elsif token.op?
> string_top = stack.pop
> string_bottom = stack.pop
> #simple logic regarding operator precedence
> stack.push("(#{string_bottom}#{token}#{string_top})") if (token
> =='+')||(token=='-')
> stack.push("#{string_bottom}#{token}#{string_top}") if (token
> =='*')||(token=='/')
> else
> #if it's not a number nor operator it's no valid
> puts "Invalid input!"
> exit(1)
> end
> }
>
> infix = stack.to_s
> #remove trailing and leading parenthesis if any
> infix = infix[1..(infix.size-2)] if
> ((infix[0]==40)&&(infix[infix.size-1]==41))
> puts infix