Skip to content

Instantly share code, notes, and snippets.

@slagyr
Created May 1, 2011 15:22
Show Gist options
  • Save slagyr/950574 to your computer and use it in GitHub Desktop.
Save slagyr/950574 to your computer and use it in GitHub Desktop.
Game of Life in 8 lines of Clojure
(defn neighbors-of [cell]
(set (for [dx [-1 0 1] dy [-1 0 1] :when (not (= [dx dy] [0 0]))]
[(+ dx (first cell)) (+ dy (second cell))])))
(defn alive? [[cell freqs] world]
(or (and (= 2 freqs) (contains? world cell)) (= 3 freqs)))
(defn tick [world]
(let [frequencies (frequencies (reduce #(concat %1 (neighbors-of %2)) [] world))]
(set (keys (filter #(alive? % world) frequencies)))))
@avysk
Copy link

avysk commented May 3, 2011

(defn neighbors-of [cell]
  (for [dx [-1 0 1] dy [-1 0 1] :when (not (= [dx dy] [0 0]))]
         (vec (map + [dx dy] cell))))

(defn alive? [world [cell freqs]]
  (when (or (and (= 2 freqs) (contains? world cell)) (= 3 freqs)) cell))

(defn tick [world]
  (let [fr (frequencies (mapcat neighbors-of world))]
    (set (keep (partial alive? world) fr))))

@slagyr
Copy link
Author

slagyr commented May 3, 2011 via email

@avysk
Copy link

avysk commented May 4, 2011

Well, you can move when -- keep #(when (alive? world %) %)
Or rename alive? to something like grow-cell :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment