Skip to content

Instantly share code, notes, and snippets.

@reborg reborg/game-of-life.clj
Last active Aug 16, 2016

What would you like to do?
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)
(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
You can’t perform that action at this time.