Created
October 2, 2014 20:01
-
-
Save trendsetter37/11fd2a10a67d8c3fe3e4 to your computer and use it in GitHub Desktop.
Prefix expressions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Ruby Prefix expressions problem on codeeval.com | |
File.open(ARGV[0]).each_line do |line| | |
# get operators using a regex | |
operators = line.scan(/[*+\/]/) #return list of operators | |
operators.reverse! | |
# This skips over spaces as well regex here once again | |
numbers = line.scan(/[^\s*+\/]/) # return list of numbers | |
answer = "" | |
numbers.each_with_index do |item, index| | |
if (index == numbers.length - 1) | |
break | |
elsif (index == 0 ) | |
# Do not forget about the float-division mentioned in the problem prompt | |
answer = eval(item.to_f.to_s + operators[index] + numbers[index + 1]) | |
else | |
answer = eval(answer.to_s + operators[index] + numbers[index + 1]) | |
end | |
end | |
# All results need to be an integer | |
puts answer.to_i | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment