burjui

Money exchange solver in Racket - flexible version

Apr 6th, 2012
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scheme 1.11 KB | None | 0 0
  1. #lang racket
  2.  
  3. (define coins (vector-immutable 50 25 10 5 1))
  4. (define coins-amount (vector-length coins))
  5.  
  6. (define cache (make-hash))
  7.  
  8. (define (count-cacher count-fn sum coin-index)
  9.   (let* ([key (cons sum coin-index)]
  10.          [entry (hash-ref cache key #f)])
  11.     (if entry
  12.         entry
  13.         (let ([result (count-fn sum coin-index)])
  14.           (hash-set! cache key result)
  15.           result))))
  16.  
  17. (define (count-exchanges sum coin-index)
  18.   (cond [(zero? sum) 1]
  19.         [(negative? sum) 0]
  20.         [(>= coin-index coins-amount) 0]
  21.         [else
  22.          (begin
  23.            (let find-smaller-coin ()
  24.              (when (and (< coin-index coins-amount)
  25.                         (< sum (vector-ref coins coin-index)))
  26.                (set! coin-index (add1 coin-index))
  27.                (find-smaller-coin)))
  28.            (+ (count-exchanges (- sum (vector-ref coins coin-index)) coin-index)
  29.               (count-exchanges sum (add1 coin-index))))]))
  30.  
  31. ;; Maybe not as cute as Python decorators, but hey - it works (:
  32. (set! count-exchanges ((curry count-cacher) count-exchanges))
  33.  
  34. (time (count-exchanges 1000000 0))
Add Comment
Please, Sign In to add comment