Last active
December 26, 2015 15:19
-
-
Save bastosmichael/7172283 to your computer and use it in GitHub Desktop.
Reverse Polish Notation Ruby Test with Standard In / Out, Error Handling and History
This file contains hidden or 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
#!/usr/bin/env ruby | |
class Controller | |
def initialize debug = false | |
puts 'Enter your Reverse Polish Notation (Example: 5 ! 1 2 + 4 * + 3 -), | |
Enter q to Quit, | |
Enter t to Test, | |
Enter d to Debug' | |
while true | |
input = $stdin.gets.strip | |
if input == 'q' then exit | |
elsif input == 't' then Test.new | |
elsif input == 'd' then debug = true; puts "Entering Debug Mode" | |
else | |
begin | |
puts "Answer: #{Calculator.new(input).answer}" | |
rescue Exception => e | |
puts "You did not use reverse polish notation" | |
puts e.message if debug | |
puts e.backtrace.inspect if debug | |
end | |
end | |
end | |
end | |
end | |
class Sum_All | |
def initialize math | |
answer = math.split(' ').inject([]) do |problem, item| | |
if item.match(/\d+/) then problem = problem.to_f + item.to_f end | |
end | |
end | |
end | |
class Calculator | |
def initialize math | |
@answer = math.split(' ').inject([]) do |problem, item| | |
@problem = problem | |
if item.match(/\d+/) then @problem << item.to_f | |
else | |
sample = @problem.pop(2) | |
case | |
when item == '!' then @problem << self.factorial(sample[0]) | |
when item == '^' then self.** sample | |
when item == '+' then self.+ sample | |
when item == '-' then self.- sample | |
when item == '*' then self.* sample | |
when item == '/' then self./ sample | |
end | |
end | |
end | |
end | |
def factorial f | |
return 1 if f == 0 | |
f * factorial(f-1) | |
end | |
def method_missing m, *args | |
@problem << eval("#{args[0][0]} #{m} #{args[0][1]}") | |
end | |
def answer | |
return @answer.pop | |
end | |
end | |
class Test | |
def initialize | |
puts "Running through test sequence" | |
self.addition "5 2 +" | |
self.subtraction "5 2 -" | |
self.multiplication "5 2 *" | |
self.division "5 2 /" | |
self.factorial "5 !" | |
self.exponents "5 2 ^" | |
self.original "5 1 2 + 4 * + 3 -" | |
self.final "5 ! 1 2 + 4 * + 3 - 2 ^" | |
end | |
def method_missing m, *args | |
answer = Calculator.new(*args).answer | |
puts "Testing #{m} #{args} = #{answer}" | |
end | |
end | |
c = Controller.new |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment