burjui

Money exchange solver in Racket - fast version

Apr 6th, 2012
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scheme 1.09 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. (define cache-width 1000001)
  6. (define cache (make-vector (* cache-width (add1 coins-amount)) #f))
  7.  
  8. (define (count-exchanges sum coin-index)
  9.   (let* ([index (+ sum (* coin-index cache-width))]
  10.          [entry (vector-ref cache index)]
  11.          [result
  12.           (cond [entry entry]
  13.                 [(zero? sum) 1]
  14.                 [(negative? sum) 0]
  15.                 [(>= coin-index coins-amount) 0]
  16.                 [else
  17.                  (begin
  18.                    (let find-smaller-coin ()
  19.                      (when (and (< coin-index coins-amount)
  20.                                 (< sum (vector-ref coins coin-index)))
  21.                        (set! coin-index (add1 coin-index))
  22.                        (find-smaller-coin)))
  23.                    (+ (count-exchanges (- sum (vector-ref coins coin-index)) coin-index)
  24.                       (count-exchanges sum (add1 coin-index))))])])
  25.     (unless entry
  26.       (vector-set! cache index result))
  27.     result))
  28.  
  29. (time (count-exchanges 1000000 0))
Add Comment
Please, Sign In to add comment