Skip to content

Instantly share code, notes, and snippets.

Created December 13, 2011 05:00
Show Gist options
  • Save anonymous/1470675 to your computer and use it in GitHub Desktop.
Save anonymous/1470675 to your computer and use it in GitHub Desktop.
;; flengyel's solution to Game of Life
;; https://4clojure.com/problem/94
(fn [board]
(letfn [ (remap [board]
(->> (for [v board]
(->> (map (fn [c] (if (= (str c) " ") 0 1)) v)
(apply vector)))
(apply vector)))
(unmap [matrix]
(->> (for [v matrix]
(->> (map (fn [b] (if (zero? b) " " "#")) v)
(apply str)))
(apply vector)))
(cneigh [matrix x y]
(let [n (count matrix)
left (mod (dec x) n)
right (mod (inc x) n)
up (mod (dec y) n)
down (mod (inc y) n)]
(->>
(for [[a b] [[left up] [x up] [right up]
[left y] [right y]
[left down][x down][right down]]]
((matrix a)b))
(reduce +))))
(nextgen [matrix]
(let [n (count matrix)]
(->>
(for [x (range n)]
(->>
(for [y (range n)]
(let [neighbors (cneigh matrix x y)]
(if (zero? ((matrix x)y))
(if (= neighbors 3) 1 0)
(cond
(or (= neighbors 2) (= neighbors 3)) 1
:else 0))))
(apply vector)))
(apply vector))))]
(->> board (remap) (nextgen) (unmap))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment