C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Change: This method checks to see if we have reached the goal. Then it tries to add a coin, placing it in a copied ArrayList.
ArrayListDisplay: This loops over all coins amounts. It counts the coins added in each amount. It displays the results.
PrintlnMain: Here we create our amounts array with coin denominations. We specify a goal of 51 cents and call change().
ArrayJava program that uses recursion, makes change
import java.util.ArrayList;
public class Program {
public static void change(ArrayList<Integer> coins, int[] amounts,
int highest, int sum, int goal) {
// See if we have reached the goal.
if (sum == goal) {
display(coins, amounts);
return;
}
// We cannot go over our goal.
if (sum > goal) {
return;
}
// Add higher amounts to a new ArrayList.
for (int value : amounts) {
if (value >= highest) {
ArrayList<Integer> copy = new ArrayList<>();
copy.addAll(coins);
copy.add(value);
// Recurse to check total and add further coins.
change(copy, amounts, value, sum + value, goal);
}
}
}
public static void display(ArrayList<Integer> coins, int[] amounts) {
// Count each amount within the added coins.
// ... Then display the amount and count.
for (int amount : amounts) {
int count = 0;
for (int coin : coins) { // Count loop.
if (coin == amount) {
count++;
}
}
System.out.print(amount);
System.out.print(":");
System.out.println(count);
}
System.out.println();
}
public static void main(String[] args) {
ArrayList<Integer> coins = new ArrayList<>();
// This array contains the coin amounts.
int[] amounts = { 1, 5, 10, 25, 50 };
// Solve for 51 cents.
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: The last result is 1 one-cent piece and 1 fifty-cent piece. It all correctly adds up.
Copy: It is important to copy a collection like an ArrayList. If the ArrayList is not copied, the algorithm will fail.
Performance: This implementation is not ideal. It could be optimized by reducing the looping in display().
Arrays: Using arrays, not ArrayLists, is typically faster. These ideas could be part of an optimization exercise.