DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

Java Counterpart of Counting Change in SICP


The following program is the Java counterpart of the counting change example at page 46 in section 1.2.2 "Tree Recursion" of "Structure and Interpretation of Computer Programs", 2nd edition.

public class CountChange { public static int first_demonstration (int kinds_of_coins) { int res = 0; switch (kinds_of_coins) { case 1: res = 1; break; case 2: res = 5; break; case 3: res = 10; break; case 4: res = 25; break; case 5: res = 50; } // System.out.println("kinds_of_coins=" + kinds_of_coins + ", return " + res); return res; }

public static void main(String[] args) { // System.out.println("args are: " + args[0] + ", " + args[1]); int res = count_change(Integer.parseInt(args[0]), Integer.parseInt(args[1])); System.out.println("Change Count is: " + res); }

public static int count_change(int amount, int kinds_of_coins) { // System.out.println("amount=" + amount + ", " + "kinds_of_coins=" + kinds_of_coins); if (amount==0) { return 1; } else if (amount<0||kinds_of_coins==0) { return 0; } else { / System.out.println("return count_change(" + amount + ", " + (kinds_of_coins - 1) + ") + count_change(" + (amount - first_demonstration(kinds_of_coins)) + ", " + kinds_of_coins + ")"); / return count_change(amount, kinds_of_coins-1) + count_change(amount - first_demonstration(kinds_of_coins), kinds_of_coins); } } }



Published

Sep 20, 2013

Last Updated

Sep 20, 2013

Category

Tech

Tags

  • Java 106
  • SICP 2

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor