Skip to content

Instantly share code, notes, and snippets.

@reborg
Last active August 16, 2016 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reborg/09752a1409688365541bda89489d2c6f to your computer and use it in GitHub Desktop.
Save reborg/09752a1409688365541bda89489d2c6f to your computer and use it in GitHub Desktop.
Game of life Clojure
(defn count-neighbors [h w x y cells]
(->> (for [dx [-1 0 1]
dy [-1 0 1]
:let [x' (+ x dx)
y' (+ y dy)]
:when (and (not (= dx dy 0))
(<= 0 x' (dec w))
(<= 0 y' (dec h)))] [x' y'])
(filter cells)
count))
(defn under? [n alive?] (and (< n 2) alive?))
(defn healthy? [n alive?] (or (and alive? (= n 2)) (= n 3)))
(defn over? [n alive?] (and (> n 3) alive?))
(defn reproduce? [n alive?] (and (= n 3) (not alive?)))
(defn apply-rules [h w x y cells]
(let [n (count-neighbors h w x y cells)
alive (contains? cells [x y])
should-live (or (healthy? n alive) (reproduce? n alive))
should-die (or (under? n alive) (over? n alive))]
(and should-live (not should-die))))
(defn next-gen [h w cells]
(into #{}
(for [x (range 0 w)
y (range 0 h)
:when (apply-rules h w x y cells)] [x y])))
;; blinker: (next-gen 5 5 #{[2 1] [2 2] [2 3]})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment