// A program to determine the minimum number of coins needed to make change. // (c) 1997 duane a. bailey import structure.*; public class RecursivePostage { static int counter; //+countImpl public static int stampCount(int amount) // pre: amount >= 0 // post: return *number* of stamps needed to make change // (only use 1 cent, 20 cent, and 32 cent stamps) { int minStamps; Assert.pre(amount >= 0,"Reasonable amount of change."); if (amount == 0) return 0; // consider use of a penny stamp minStamps = 1+stampCount(amount-1); // consider use of a 20 cent stamp if (amount >= 20) { int possible = 1+stampCount(amount-20); if (minStamps > possible) minStamps = possible; } // consider use of a 32 cent stamp if (amount >= 32) { int possible = 1+stampCount(amount-32); if (minStamps > possible) minStamps = possible; } return minStamps; } //-countImpl public static void main(String args[]) { counter = 0; System.out.println("Stamps returned to make 42 cents: "+ stampCount(42)); System.out.println(counter); } //+coinsImpl public static coins change(int amount) { Assert.pre(amount >= 0, "Amount must be positive."); coins best, possible; if (amount == 0) best = new coins(); else { possible = change(amount-1); possible.addPenny(); best = possible; if (amount >= 5) { possible = change(amount-5); possible.addNickle(); if (best.total() > possible.total()) best = possible; } if (amount >= 10) { possible = change(amount-10); possible.addDime(); if (best.total() > possible.total()) best = possible; } if (amount >= 25) { possible = change(amount-25); possible.addQuarter(); if (best.total() > possible.total()) best = possible; } } return new coins(best); } //-coinsImpl } class coins { int pennies, nickles, dimes, quarters; public coins() { pennies = nickles = dimes = quarters = 0; } public coins(coins that) { this.pennies = that.pennies; this.nickles = that.nickles; this.dimes = that.dimes; this.quarters = that.quarters; } public void addPenny() { pennies++; } public void addNickle() { nickles++; } public void addDime() { dimes++; } public void addQuarter() { quarters++; } public int total() { return pennies+nickles+dimes+quarters; } public String toString() { return "pennies: "+pennies+", nickles: "+nickles+ ", dimes: "+dimes+", quarters: "+quarters; } }