1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
def make_change(amount, coins = [100, 50, 20, 10, 5, 1, 0.5, 0.1]) coins.sort! { |x, y| y <=> x } return coins.map!{ |coin| f = amount/coin amount %= coin Array.new(f){coin} }.flatten end def make_change(amount, coins = [100, 50, 20, 10, 5, 1, 0.5, 0.1]) change = [] coins.each do |coin| (amount / coin).times do change << coin amount -= coin end end change if amount.zero? end
Refactorings
No refactoring yet !
Wolfbyte
July 26, 2010, July 26, 2010 08:39, permalink
Here's a recursive version. It's probably not particularly efficient because it has to search through the coins array over and over again. There are ways you could fix that but the start to impact the readability of the algorithm.
1 2 3 4 5 6 7 8 9
def make_change(amount, coins = [100, 50, 20, 10, 5, 1, 0.5, 0.1]) make_change_rec(amount, coins.sort { |a,b| b <=> a }) end def make_change_rec(amount, coins) coin = coins.find { |x| x <= amount } return [] if coin.nil? [coin, *make_change_rec(amount - coin, coins)] end
change coins