Skip to content

Instantly share code, notes, and snippets.

@ahjones
Created November 9, 2012 21:40
Show Gist options
  • Save ahjones/4048429 to your computer and use it in GitHub Desktop.
Save ahjones/4048429 to your computer and use it in GitHub Desktop.
Clojure Game of Life
(defn show-line [l]
(apply str (map #(if (= 1 %) \x \space) l)))
(defn show [w]
(str "\n----\n"
(apply str (interpose \newline (map show-line w)))
"\n----\n"))
(defn get-cell [w x y]
(if (and (< -1 x (count (first w)))
(< -1 y (count w)))
(get-in w [y x])
0))
(defn neighbours [w x y]
(- (reduce +
(for [dx [-1 0 1] dy [-1 0 1]]
(get-cell w (+ x dx) (+ y dy))))
(get-cell w x y)))
(defn next-gen [w]
(let [vmi (comp vec map-indexed)]
(vmi (fn [yi y]
(vmi (fn [xi x]
(let [n (neighbours w xi yi)]
(if (= x 1)
(cond
(< n 2) 0
(<= 2 n 3) 1
(< 3 n) 0)
(if (= n 3) 1 0)))) y)) w)))
(def glider [[0 0 1 0 0]
[1 0 1 0 0]
[0 1 1 0 0]
[0 0 0 0 0]
[0 0 0 0 0]])
(print (map show (take 5 (iterate next-gen glider))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment