C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: If we have reached 51 cents exactly, we call display(), which loops through and displays the counts of all coin denominations.
For: We use a for-in loop on the amounts of coins and add only larger or equal-sized coins.
ForArray: We copy our array of coins with an Array init. It is important to copy our array, as many code paths may act on the array argument.
ArrayFinally: We use recursion to call the change() func from within change. No special keywords are needed.
Swift program that uses recursion
func change(coins: [Int],
amounts: [Int],
highest: Int,
sum: Int,
goal: Int) {
// See if our goal has been reached.
if sum == goal {
display(coins, amounts: amounts)
return
}
// Do not continue if we are past the goal.
if sum > goal {
return
}
// Try to add a coin in each possible size.
for value in amounts {
// Only add increasingly large coins.
if value >= highest {
// Copy the array and add this value to it.
var copy = Array(coins)
copy.append(value)
// Try to add more coins.
change(copy,
amounts: amounts,
highest: value,
sum: sum + value,
goal: goal)
}
}
}
func display(coins: [Int], amounts: [Int]) {
// Loop over amounts.
for amount in amounts {
// Count all coins with the current amount.
var count = 0
for coin in coins {
if coin == amount {
count++
}
}
// Display the number of coins of this amount.
print("\(amount): \(count)")
}
print("")
}
var coins: [Int] = []
var amounts: [Int] = [1, 5, 10, 25, 50]
// Start adding coins.
change(coins,
amounts: amounts,
highest: 0,
sum: 0,
goal: 51)
Output
1: 51
5: 0
10: 0
25: 0
50: 0
1: 46
5: 1
10: 0
25: 0
50: 0
1: 41
5: 2
10: 0
25: 0
50: 0
...
1: 1
5: 0
10: 0
25: 2
50: 0
1: 1
5: 0
10: 0
25: 0
50: 1
Quote: We can easily translate this description into a recursive procedure (Structure and Interpretation of Computer Programs).