Unclear why this coin change algorithm works -


i worked yesterday on getting coin changing algorithm work.

it seems me that,

  1. first, makechange1() calls getchange1() change amount...
  2. getchange1() checks if amount == 0, if so, print list
  3. if amount >= current denomination, add denomination list recur, decrementing amount current denomination...
  4. if amount < current denomination, recurs on next denomination... (index + 1)

i don't understand how getchange() called again once amount equals 0... doesn't if amount == 0, print out list?

    if (amount == 0) {         system.out.print(total + ", ");     } 

therefore, because of i'm not sure how rest of permutations completed... a picture 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!

it's not else-if , method doesn't return after printing out list.

once prints out line, continue

if (index + 1 < denominations.length)   {     getchange1(amount, total, index+1); } 

which call function again incremented index.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -