Skip to content

Instantly share code, notes, and snippets.

@aquajach
Created April 26, 2016 03:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aquajach/58036540f7935cdafe7cfca5c90e0c4a to your computer and use it in GitHub Desktop.
Save aquajach/58036540f7935cdafe7cfca5c90e0c4a to your computer and use it in GitHub Desktop.
Coin changes solved by recursion
def coin_change(coins, amount)
coins = coins.sort
coin = coins.first
multiples = (0..(amount / coin)).map{|division| division * coin}
solution = amount
if coins.count == 1
if amount % coin != 0
return -1
else
return amount / coin
end
else
coins.shift
multiples.each_with_index do |multiple, index|
if index < solution
result = coin_change(coins, amount - multiple)
if result != -1
solution = [index + result, solution].min
end
end
end
end
solution == amount ? -1 : solution
end
puts "#{coin_change([470,35,120,81,121], 9825)}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment