package username.dynamic; /** * A simple program to compute the fewest coins for a particular * price. * * @author Samuel A. Rebelsky * @author CSC152 2006S * @version 1.0 of April 2006 */ public class BetterCoins { /** * Given a set of denominations, compute the fewest coins * for a particular price. */ public static int[] fewestCoins(int[] denominations, int price) throws Exception { int[] cache = new int[price+1]; int[][] newcache = new int[price+1][denominations.length]; fewestCoins(denominations, price, cache, newcache); // Tony: Return the "alternate cache" return newcache[price]; } public static int fewestCoins(int[] denominations, int price, int[] cache, int[][] newcache) throws Exception { // Sanity check if (price < 0) { throw new Exception("Invalid price"); } // Easy case: No cost implies no coins else if (price == 0) { return 0; } else if (cache[price] == -1) { // Betsy: We need to check cache[0][price] instead throw new Exception("Cannot make change for " + price); } else if (cache[price] != 0) { // Betsy: Check if any of the slots has 0 // Tony: Return results[price] return cache[price]; } // Normal case: Check each coin and see which one works best. else { int best = Integer.MAX_VALUE; for (int i = 0; i < denominations.length; i++) { int newprice = price - denominations[i]; if (newprice >= 0) { try { // Betsy: Sum the values in the array // Tony: Use the original cache int guess = fewestCoins(denominations, newprice, cache, newcache); if (guess < best) { best = guess+1; // Betsy: Grab the subarray from the best one and increment the number of the given coin for (int j = 0; j < denominations.length; j++) { newcache[price][j] = newcache[newprice][j]; } // for newcache[price][i] = newcache[price][i]+1; // Tony: Set the values in the parallel array cache[price] = best; } } // try catch (Exception e) { // Of well, that coin didn't work. } // catch(Exception } // if (newprice >= 0) } // for if (best != Integer.MAX_VALUE) { return cache[price]; } else { cache[price] = -1; throw new Exception("Cannot make exact change for " + price); } } // normal case } // fewestCoins(int[], int) } // class BetterCoins