package username.dynamic; import java.util.Vector; /** * 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 NewerCoins { /** * Given a set of denominations, compute the fewest coins * for a particular price. */ public static Vector fewestCoins(int[] denominations, int price) throws Exception { // Sanity check if (price < 0) { throw new Exception("Invalid price"); } // Easy case: No cost implies no coins else if (price == 0) { return new Vector(); } // Normal case: Check each coin and see which one works best. else { Vector best = null; for (int i = 0; i < denominations.length; i++) { int newprice = price - denominations[i]; if (newprice >= 0) { try { Vector guess = fewestCoins(denominations, newprice); if ((best == null) || (guess.size() < best.size())) { best = (Vector) guess.clone(); best.add(new Integer(denominations[i])); } } // try catch (Exception e) { // Of well, that coin didn't work. } // catch(Exception } // if (newprice >= 0) } // for if (best != null) { return best; } else { throw new Exception("Cannnot make exact change for " + price); } } // normal case } // fewestCoins(int[], int) } // class NewerCoins