<< Previous exercise (2.18) | Index | Next exercise (2.20) >>
this also works
(define no-more? null?) (define except-first-denomination cdr) (define first-denomination car)
For the last part of the exercise. The order of the coins does not affect the result. Becuase the procedure computes all possible combinations. But it does affect the speed of the computation. If you start with the lower valued coins, it'll take much longer.
(define (timed-cc amount coin-values start-time) (cc amount coin-values) (- (runtime) start-time)) (timed-cc 200 us-coins (runtime)) ;.6799 (timed-cc 200 (reverse us-coins) (runtime)) ;1.27 (if (> (timed-cc 100 (reverse us-coins) (runtime)) (timed-cc 100 us-coins (runtime))) (display "Reverse takes longer") (display "Reverse does not take longer")) ;As expected, reverse takes longer
@Rptx: It is slower because of the recursive calls calling reverse everytime. If I put a list in reversed order as argument I do not notice any speed penalty.
Please see https://people.eecs.berkeley.edu/~bh/61a-pages/Volume1/labs.pdf Week 3 problem 2 and its solution https://people.eecs.berkeley.edu/~bh/61a-pages/Solutions/week3.
Using other methods to achieve the same function
;; functional programming (define (count-change-1 amount denomination-list) (length (filter (lambda (data) (= amount (apply + (map * data denomination-list)))) (accumulate (lambda (a-list b-list) (flatmap (lambda (a) (map (lambda (b) (cons a b)) b-list)) a-list)) (list '()) (map (lambda (c) (enumerate-interval 0 c)) (map (lambda (d) (floor (/ amount d))) denomination-list)))))) ;; Using nested mappings (define (nested-map mapping op keys-list) (define (rec keys-list args) (if (null? keys-list) (apply op (reverse args)) (mapping (lambda (key) (rec (cdr keys-list) (cons key args))) (car keys-list)))) (rec keys-list '())) (define (count-change-2 amount denomination-list) (let ((count 0)) (define (count-inc! . b) (if (= amount (apply + (map * b denomination-list))) (set! count (+ count 1)))) (nested-map for-each count-inc! (map (lambda (c) (enumerate-interval 0 c)) (map (lambda (d) (floor (/ amount d))) denomination-list))) count))
It's a bit beyond the book intention since it is not to teach the Scheme syntax. This is a bit unnecessarily complexer.
<< Previous exercise (2.18) | Index | Next exercise (2.20) >>
jz