schlayer

ChangeMaking

Nov 30th, 2016
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.90 KB | None | 0 0
  1.  
  2.     public static int[] makeChange(int amount, int[] denominations) {
  3.         calls = 0;
  4.        
  5.         int L = denominations.length;
  6.         int[] counts = new int[L + 1];
  7.        
  8.         recMakeChange(amount, denominations, counts);
  9.        
  10.         //for(int d: counts) System.out.println(d);
  11.  
  12.         int[] solution = new int[counts[L]]; // length is number of tokens
  13.         int i = 0;
  14.         // For each index of counts referring to a denomination
  15.         for(int j = 0; j < counts.length-1; j++) {
  16.             // Loop x times where x is the # of that denomination needed
  17.             for (int x = 0; x < counts[j]; x++) {
  18.                 solution[i] = denominations[j];
  19.                 // Put the needed denom in the solutions array x times
  20.                 i++;
  21.             }
  22.         }
  23.        
  24.         System.out.println("Finding change for: " + amount);
  25.         System.out.println("Sum of solutions array: " + sumArr(solution));
  26.         System.out.println("Required " + calls + " calls.");
  27.        
  28.         return solution;
  29.     }
  30.    
  31.    
  32.     public static boolean recMakeChange(int amount, int[] denom, int[] counts) {
  33.         calls++;
  34.        
  35.         if (amount == 0)  return true;
  36.         if (amount < 0) return false;
  37.         if (table[amount] != null) {
  38.             for (int k = 0; k < table[amount].length; k++)
  39.                 counts[k] = table[amount][k];
  40.             return true;
  41.         }
  42.        
  43.         boolean ret = false;
  44.         int[] temp = new int[counts.length];
  45.         int[] best = new int[counts.length];
  46.         best[best.length-1] = amount + 1;
  47.  
  48.         for (int i = 0; i < denom.length; i++) {
  49.            
  50.             if (recMakeChange(amount - denom[i], denom, temp)) {
  51.                 if (temp[temp.length-1] < best[best.length-1]) {
  52.                     temp[i]++;
  53.                     temp[temp.length-1]++;
  54.                     for(int z = 0; z<best.length;z++)
  55.                         best[z] = temp[z];
  56.                 }
  57.                 ret = true;
  58.             }
  59.         }
  60.        
  61.         // Copy best into counts if solution is found...
  62.         if (ret) {
  63.             for(int n = 0; n < best.length; n++) counts[n] = best[n];
  64.             table[amount] = new int[counts.length];
  65.             for(int z = 0; z < best.length; z++)
  66.                 table[amount][z] = counts[z] = best[z];
  67.         }
  68.  
  69.         return ret;
  70.  
  71.     }
Advertisement
Add Comment
Please, Sign In to add comment