Skip to content

Instantly share code, notes, and snippets.

@dbasch
Last active December 25, 2015 05:19
Show Gist options
  • Save dbasch/6923514 to your computer and use it in GitHub Desktop.
Save dbasch/6923514 to your computer and use it in GitHub Desktop.
(defn next-gen [b r c]
(let [neighbors (fn [[cell :as [i j]]]
(remove #(= % [i j])
(for [x (filter (-> r range set) (range (- i 1) (+ 2 i)))
y (filter (-> c range set) (range (- j 1) (+ 2 j)))]
[x y])))
alive? (fn [[cell :as [i j]]]
(nth (nth b i) j))]
(for [i (range r)]
(for [j (range c)]
(let [live-nb (count (filter true? (map alive? (neighbors [i j]))))]
(or (= 3 live-nb) (and (alive? [i j]) (= 2 live-nb))))))))
(defn life [r c]
(loop [x 100
b (partition r (take (* c r) (repeatedly #(zero? (rand-int 5)))))]
(let [nb (next-gen b r c)
delim (str \+ (apply str (repeat (count (first b)) \-)) \+)
render (apply str (for [r nb] (str "|" (apply str (map #(if % \# \space) r)) "|\n")))]
(println (str (apply str (repeat 50 "\n")) delim "\n" render delim))
(Thread/sleep 100)
(if (and (pos? x) (not= nb b))
(recur (dec x) nb)
(println "\nStopped after" (- 100 x) "iterations" (if (zero? x) "(limit)" ""))))))
(life 20 20)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment