Skip to content

Instantly share code, notes, and snippets.

@trendsetter37
Created October 2, 2014 20:01
Show Gist options
  • Save trendsetter37/11fd2a10a67d8c3fe3e4 to your computer and use it in GitHub Desktop.
Save trendsetter37/11fd2a10a67d8c3fe3e4 to your computer and use it in GitHub Desktop.
Prefix expressions
#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