Here is my iterative implementation of the Counting change example in SICP. Please note that I'm a beginner, which means I only know the basic syntax for the time being.
Requirement:
How many different ways can we make change of $ 1.00, given half-dollars, quarters, dimes, nickels, and pennies? More generally, can we write a procedure to compute the number of ways to change any given amount of money?
Code:
(define (count-change-iterative amount)
;; penny is not in the signiture, bacause it equals (- amount
;; (* half-dollar 50)
;; (* quarter 25)
;; (* dime 10)
;; (* nickeli 5))
(define (count-iter half-dollar quarter dime nickeli)
(cond ((> (* half-dollar 50) amount)
0)
((> (+ (* half-dollar 50)
(* quarter 25)) amount)
(count-iter (+ half-dollar 1) 0 0 0))
((> (+ (* half-dollar 50)
(* quarter 25)
(* dime 10)) amount)
(count-iter half-dollar (+ quarter 1) 0 0))
((> (+ (* half-dollar 50)
(* quarter 25)
(* dime 10)
(* nickeli 5)) amount)
(count-iter half-dollar quarter (+ dime 1) 0))
(else (+ 1
(count-iter half-dollar quarter dime (+ nickeli 1))))))
(count-iter 0 0 0 0))
If you run (count-change-iterative 100)
, it would tell you 292
.
I think this is the best scheme code I've written by now. How can I improve it?