fork download
  1. ; the rat eats the cheese
  2.  
  3. (define-syntax define-memoized
  4. (syntax-rules ()
  5. ((define-memoized (f arg ...) body ...)
  6. (define f
  7. (let ((cache (list)))
  8. (lambda (arg ...)
  9. (cond ((assoc `(,arg ...) cache) => cdr)
  10. (else (let ((val (begin body ...)))
  11. (set! cache (cons (cons `(,arg ...) val) cache))
  12. val)))))))))
  13.  
  14. (define (make-cheese n fill)
  15. (define (rand-row)
  16. (let ((row (make-vector n 0)))
  17. (do ((k 0 (+ k 1))) ((= k n) row)
  18. (when (< (random 1.0) fill)
  19. (vector-set! row k 1)))))
  20. (set! nrows n) (set! ncols n)
  21. (let ((rows (make-vector n #f)))
  22. (do ((k 0 (+ k 1))) ((= k n))
  23. (vector-set! rows k (rand-row)))
  24. rows))
  25.  
  26. (define nrows #f) (define ncols #f)
  27. (define cheese (make-cheese 20 0.15))
  28.  
  29. (for-each
  30. (lambda (row) (display row) (newline))
  31. (vector->list cheese))
  32. (newline)
  33.  
  34. (define-memoized (rat r c)
  35. (if (or (= r nrows) (= c ncols)) 0
  36. (+ (vector-ref (vector-ref cheese r) c)
  37. (max (rat (+ r 1) c) (rat r (+ c 1))))))
  38.  
  39. (display (rat 0 0)) (newline)
Success #stdin #stdout 0.03s 50592KB
stdin
Standard input is empty
stdout
#(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0)
#(0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0)
#(0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0)
#(0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0)
#(0 0 1 0 0 0 1 0 0 1 0 0 0 0 0 0 0 1 1 0)
#(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1)
#(0 0 0 0 0 0 1 0 0 0 1 0 1 0 0 0 0 1 0 0)
#(0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)
#(0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0)
#(1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 1 0)
#(0 0 0 0 0 1 0 0 1 0 0 0 1 0 0 0 1 0 0 0)
#(0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0)
#(0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0)
#(0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0)
#(0 0 0 1 0 0 0 1 0 0 0 1 0 0 1 0 0 0 0 0)
#(0 0 0 0 0 0 0 0 1 0 0 0 0 1 1 0 0 1 0 0)
#(0 1 0 0 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0)
#(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)
#(0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0)
#(0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 1 1 0 1)

13