Skip to content

Instantly share code, notes, and snippets.

@chewbakartik
Created June 19, 2018 23:19
Show Gist options
  • Save chewbakartik/bee667ebaf4b7c4c3928fa50b5ab824f to your computer and use it in GitHub Desktop.
Save chewbakartik/bee667ebaf4b7c4c3928fa50b5ab824f to your computer and use it in GitHub Desktop.
Cash Register
class CashRegister
US_COINS = {"quarter" => 25, "dime" => 10, "nickel" => 5, "penny" => 1 }
EU_COINS = {"50_cent" => 50, "20_cent" => 20, "10_cent" => 10, "5_cent" => 5, "2_cent" => 2, "1_cent" => 1 }
def self.get_change(cash, currency)
cash_left = cash
coin_numbers = Hash.new
coins = self.get_coins(currency)
# determine the quantity of each coin starting from the largest value
coins.each {|coin, value|
num_coins = cash_left / value
cash_left = cash_left - (num_coins * value)
coin_numbers[coin] = num_coins
}
coin_numbers
end
def self.get_coins(currency)
case currency
when "EU"
EU_COINS
when "US"
US_COINS
else
raise CurrencyError, "Unsupported currency"
end
end
end
class CurrencyError < StandardError
end
require_relative "cash_register"
require "test/unit"
class TestCashRegister < Test::Unit::TestCase
def test_get_change_us
coin_numbers = CashRegister.get_change(63, "US")
assert_equal(coin_numbers["quarter"], 2)
assert_equal(coin_numbers["dime"], 1)
assert_equal(coin_numbers["nickel"], 0)
assert_equal(coin_numbers["penny"], 3)
coin_numbers = CashRegister.get_change(117, "US")
assert_equal(coin_numbers["quarter"], 4)
assert_equal(coin_numbers["dime"], 1)
assert_equal(coin_numbers["nickel"], 1)
assert_equal(coin_numbers["penny"], 2)
end
def test_get_change_eu
coin_numbers = CashRegister.get_change(63, "EU")
assert_equal(coin_numbers["50_cent"], 1)
assert_equal(coin_numbers["20_cent"], 0)
assert_equal(coin_numbers["10_cent"], 1)
assert_equal(coin_numbers["5_cent"], 0)
assert_equal(coin_numbers["2_cent"], 1)
assert_equal(coin_numbers["1_cent"], 1)
coin_numbers = CashRegister.get_change(88, "EU")
assert_equal(coin_numbers["50_cent"], 1)
assert_equal(coin_numbers["20_cent"], 1)
assert_equal(coin_numbers["10_cent"], 1)
assert_equal(coin_numbers["5_cent"], 1)
assert_equal(coin_numbers["2_cent"], 1)
assert_equal(coin_numbers["1_cent"], 1)
coin_numbers = CashRegister.get_change(85, "EU")
assert_equal(coin_numbers["50_cent"], 1)
assert_equal(coin_numbers["20_cent"], 1)
assert_equal(coin_numbers["10_cent"], 1)
assert_equal(coin_numbers["5_cent"], 1)
assert_equal(coin_numbers["2_cent"], 0)
assert_equal(coin_numbers["1_cent"], 0)
end
def test_unsupported_currency
assert_raises CurrencyError do
CashRegister.get_change(100, "CA")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment