Last active
August 29, 2015 14:01
-
-
Save kencrocken/0f9e03a3f331b45083c9 to your computer and use it in GitHub Desktop.
How much change do you have?
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
def make_change(amount, coins = [25,10,5,1]) | |
puts "Input doesn't make sense. You have change leftover." if amount % coins.last != 0 | |
change = {} | |
coins.each do |coin| | |
x = amount/coin | |
amount = amount - (x * coin) | |
coin_key = coin.to_s | |
change[coin_key] = x | |
end | |
change.each {|k,v| puts "You have #{v}, #{k} cent coin(s)" if v > 0} | |
puts "You have #{amount} cent left over, with no corresponding coin." if amount > 0 | |
end | |
make_change(41) | |
make_change(352) | |
make_change(174,[17,6,2]) | |
make_change(175,[17,6,2]) | |
############################################### | |
def make_change(amount) | |
coins = [25,10,5,1] | |
change = {} | |
coins.each do |coin| | |
x = amount/coin | |
amount = amount - (x * coin) | |
coin = "quarters".to_sym if coin == 25 | |
coin = "dimes".to_sym if coin == 10 | |
coin = "nickels".to_sym if coin == 5 | |
coin = "pennies".to_sym if coin == 1 | |
change[coin] = x | |
end | |
change | |
end | |
#### This one feels like cheating | |
def make_change(amount) | |
coins = { quarters: 25, dimes: 10, nickels: 5, pennies: 1 } | |
change = {} | |
coins.each do |key,coin| | |
x = amount/coin | |
amount = amount - (x * coin) | |
change[key] = x | |
end | |
change | |
end | |
############################################### | |
puts make_change(1) == {quarters: 0, dimes: 0, nickels:0, pennies: 1 } | |
puts make_change(5) == {quarters: 0, dimes: 0, nickels:1, pennies: 0 } | |
puts make_change(6) == {quarters: 0, dimes: 0, nickels:1, pennies: 1 } | |
puts make_change(32) == {quarters: 1, dimes: 0, nickels:1, pennies: 2 } | |
puts make_change(41) == {quarters: 1, dimes: 1, nickels:1, pennies: 1 } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment