I worked with someone yesterday from SO on getting my coin changing algorithm to work.
It seems to me that,
- first,
makeChange1()
callsgetChange1()
with the change amount... getChange1()
checks if amount == 0, if so, it will print the list- if
amount >= current denomination
, it will add that denomination to the list then recur, decrementing the amount by the current denomination... - if
amount < current denomination
, it recurs on to the next denomination... (index + 1)
I don't understand how getChange()
will be called again once the amount equals 0... doesn't it just say that if amount == 0, it will just print out the list?
if (amount == 0) {
System.out.print(total + ", ");
}
Therefore, because of this I'm not sure how the rest of the permutations will be completed... A picture would reallly help!
Input:
12 cents
Output:
[10, 1, 1], [5, 5, 1, 1], [5, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
Code:
public void makeChange1(int amount) {
getChange1(amount, new ArrayList<Integer>(), 0);
}
public void getChange1(int amount, List<Integer> total, int index) {
int[] denominations = {25, 10, 5, 1};
if (amount == 0) {
System.out.print(total + ", ");
}
if (amount >= denominations[index]) {
total.add(denominations[index]);
getChange1(amount-denominations[index], total, index);
total.remove(total.size()-1);
}
if (index + 1 < denominations.length) {
getChange1(amount, total, index+1);
}
}
Thanks!