Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #lang racket
- (define coins (vector-immutable 50 25 10 5 1))
- (define coins-amount (vector-length coins))
- (define cache (make-hash))
- (define (count-cacher count-fn sum coin-index)
- (let* ([key (cons sum coin-index)]
- [entry (hash-ref cache key #f)])
- (if entry
- entry
- (let ([result (count-fn sum coin-index)])
- (hash-set! cache key result)
- result))))
- (define (count-exchanges sum coin-index)
- (cond [(zero? sum) 1]
- [(negative? sum) 0]
- [(>= coin-index coins-amount) 0]
- [else
- (begin
- (let find-smaller-coin ()
- (when (and (< coin-index coins-amount)
- (< sum (vector-ref coins coin-index)))
- (set! coin-index (add1 coin-index))
- (find-smaller-coin)))
- (+ (count-exchanges (- sum (vector-ref coins coin-index)) coin-index)
- (count-exchanges sum (add1 coin-index))))]))
- ;; Maybe not as cute as Python decorators, but hey - it works (:
- (set! count-exchanges ((curry count-cacher) count-exchanges))
- (time (count-exchanges 1000000 0))
Add Comment
Please, Sign In to add comment