Created
March 16, 2016 04:33
-
-
Save TikiTDO/ce53c9c0796bb0b6fa9b to your computer and use it in GitHub Desktop.
Coin Change Solver
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
require 'rubygems' | |
require 'pry' | |
VALID_COINS = [1, 5, 10, 25, 50] | |
def change(amount) | |
change_iter(amount, VALID_COINS).each do |item| | |
puts item.inspect | |
end | |
end | |
def change_iter(amount, coin_list) | |
first_coin = coin_list.first | |
amount_after_first = amount - first_coin | |
if amount_after_first == 0 | |
return [[first_coin]] | |
elsif amount_after_first < 0 | |
return [] | |
else | |
ret = change_iter(amount_after_first, coin_list).map do |item| | |
item.push(first_coin) | |
end | |
ret += change_iter(amount, coin_list[1..-1]) do |item| | |
item.push(first_coin) | |
end | |
return ret | |
end | |
end | |
change(45) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment