PasteRack.org
Paste # 47617
2016-10-22 06:17:37

Fork as a new paste.

Paste viewed 61 times.


Embed:

TDD-ing Game of Life

  1. #lang racket
  2.  
  3. (require rackunit)
  4.  
  5. ; alive : (List (List Bool)) Integer Integer -> Bool
  6. ; Is the cell at (r,c) on grid alive?
  7. (define (alive? grid r c)
  8.   (if (or (< r 0)
  9.           (< c 0)
  10.           (>= r (length grid))
  11.           (>= c (length grid)))
  12.          #f
  13.          (list-ref (list-ref grid r) c)))
  14.  
  15. ; make-empty-grid : Integer -> (List (List Bool))
  16. ; Make an n x n empty grid (i.e. all values are #f)
  17. (define (make-empty-grid n)
  18.   (make-list n (make-list n #f)))
  19.  
  20.  
  21. (define (boolean->number b)
  22.   (if b 1 0))
  23.  
  24. ; How many live neighbors does the cell (r,c) in grid have?
  25. (define (neighbors grid r c)
  26.   (+ (boolean->number (alive? grid (sub1 r) (sub1 c)))
  27.      (boolean->number (alive? grid (sub1 r) c))
  28.      (boolean->number (alive? grid (sub1 r) (add1 c)))
  29.  
  30.      (boolean->number (alive? grid r (sub1 c)))
  31.      ;(boolean->number (alive? grid r c))
  32.      (boolean->number (alive? grid r (add1 c)))
  33.  
  34.      (boolean->number (alive? grid (add1 r) (sub1 c)))
  35.      (boolean->number (alive? grid (add1 r) c))
  36.      (boolean->number (alive? grid (add1 r) (add1 c)))))
  37.  
  38.  
  39. ;; TESTS
  40. ;;
  41. (define test-grid '((#f #t) (#t #f)))
  42. (check-equal? (alive? test-grid 0 0) #f)
  43. (check-equal? (alive? test-grid 0 1) #t)
  44. (check-equal? (alive? test-grid 1 0) #t)
  45. (check-equal? (alive? test-grid 1 1) #f)
  46. (check-equal? (alive? test-grid -1 0) #f)
  47. (check-equal? (alive? test-grid 0 -1) #f)
  48. (check-equal? (alive? test-grid 2 0) #f)
  49. (check-equal? (alive? test-grid 0 2) #f)
  50.  
  51. (check-equal? (make-empty-grid 2) '((#f #f) (#f #f)))
  52.  
  53. (check-equal? (neighbors test-grid -1 -1) 0)
  54. (check-equal? (neighbors test-grid 0 0) 2)
  55.  
  56.  
  57. (check-equal? (boolean->number #f) 0)
  58. (check-equal? (boolean->number #t) 1)

=>