-
-
Save dinedal/8b76a83a3c8b17ad8634 to your computer and use it in GitHub Desktop.
This file contains 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
## Ways to make change | |
# | |
# Submitter: Paul Bergeron - paul.d.bergeron@gmail.com | |
# Website: pauldbergeron.com | |
# Github: https://github.com/dinedal | |
# Location: San Francisco - CA | |
# | |
# Recursive solution, will blow the stack with large values, but memoizes so it trades | |
# memory for increased speed. | |
coin_types = gets.split(", ").map(&:to_i) | |
make_change_val = gets.to_i | |
class ChangeMaker | |
def initialize | |
@memo = {} | |
end | |
def make_change(coins, val) | |
# Check stop conditions | |
if coins.length == 0 # No coins to deal with, no ways to make change | |
0 | |
elsif coins.length == 1 # One coin | |
val % coins[0] == 0 ? 1 : 0 # If it's divisable by the coin, it's one way, else no ways | |
else | |
# Real meat of the loop, check the this coin against combinations of other coins | |
number_of_ways = 0 | |
this_coin = coins.first | |
other_coins = coins[1..-1] | |
i = 0 | |
while(val - i * this_coin >= 0) # iterate, each step of the coin's value | |
args = [other_coins, val - i * this_coin] # args is the memoized key | |
# prefer the memo, otherwise count what other ways the other coins can make change | |
number_of_ways += (@memo[args] ||= make_change(*args)) | |
i += 1 | |
end | |
number_of_ways | |
end | |
end | |
end | |
cm = ChangeMaker.new | |
puts cm.make_change(coin_types.sort.uniq, make_change_val) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice code! If you rename the gist filename to .rb it will look even prettier! :)