Skip to content

Instantly share code, notes, and snippets.

@MayDaniel
Forked from slagyr/gist:950574
Created May 1, 2011 16:24
Show Gist options
  • Save MayDaniel/950619 to your computer and use it in GitHub Desktop.
Save MayDaniel/950619 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))))

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