C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Change: This is a recursive method. It first checks to see if we have collected our goal amount. Then it tries to add new coins in a loop.
forInfo: When we find a coin to add, in change, we copy our coins list with a slice. Then we append the new coin.
And: It is important to copy, as each recursive call must have its own list. When we reach our goal amount, we display our coins.
Copy ListDisplay: This def-method loops over all possible amounts, and displays the number of coins collected by amount.
Python program that uses recursion
def change(coins, amounts, highest, sum, goal):
# See if we are done.
if sum == goal:
display(coins, amounts)
return
if sum > goal:
return
for value in amounts:
if value >= highest:
# Copy the coins list, then add the current value.
copy = coins[:]
copy.append(value)
# Recursively add more coins.
change(copy, amounts, value, sum + value, goal)
def display(coins, amounts):
# Display our coins sorted by amount.
for amount in amounts:
count = coins.count(amount)
print(amount, ":", count)
print("")
coins = []
amounts = [1, 5, 10, 25, 50]
# Begin.
change(coins, amounts, 0, 0, 51)
Output
1 : 51
5 : 0
10 : 0
25 : 0
50 : 0
1 : 46
5 : 1
10 : 0
25 : 0
50 : 0
...
1 : 1
5 : 0
10 : 0
25 : 0
50 : 1
Finally: In the last result, shown after many skipped results, we use 1 one-cent coin and a 50-cent coin.
And: We only add coins of greater or equal value as we progress (in change). This makes the search much simpler as well.
Tip: Solving game problems, like puzzles, with recursive methods like this one is an excellent learning exercise.