Created
November 14, 2014 11:16
-
-
Save nicohvi/9e5911c2d2e88128cbe7 to your computer and use it in GitHub Desktop.
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
require 'minitest/autorun' | |
require 'byebug' | |
def stack_machine(string) | |
result = [] | |
numbers = [] | |
string.split.each do |token| | |
if /(\d)/.match(token) | |
numbers << Integer(token) | |
else | |
result << numbers.reduce(&token.to_sym) | |
numbers.clear | |
end | |
end | |
result | |
end | |
class StackMachineTest < MiniTest::Test | |
def test_addition | |
assert_equal [3, 6, 8], stack_machine('1 2 + 3 3 + 4 4 +') | |
end | |
def test_multiplication | |
assert_equal [9, 12, 28], stack_machine('3 3 * 3 4 * 7 4 *') | |
end | |
def test_division | |
assert_equal [4, 3, 2], stack_machine('8 2 / 9 3 / 148 74 /') | |
end | |
def test_subtraction | |
assert_equal [99, 567, 5], stack_machine('100 1 - 965 398 - 15 10 -') | |
end | |
def test_multiple_arguments | |
assert_equal [3, 6, 99], stack_machine('1 1 1 + 3 2 * 199 50 50 -') | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment