Created
October 7, 2013 17:50
-
-
Save elfenlaid/6872060 to your computer and use it in GitHub Desktop.
solution to http://www.4clojure.com/problem/94
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn board-step [board] | |
(let [live-cell \# | |
dead-cell \space | |
live-cell? (fn [cell] (= cell live-cell)) | |
transit-cell (fn [cell live-neib] | |
(if (live-cell? cell) | |
(cond | |
(< live-neib 2) dead-cell | |
(> live-neib 3) dead-cell | |
:else live-cell) | |
(cond | |
(= live-neib 3) live-cell | |
:else dead-cell))) | |
align-subvec (fn [v f t] | |
(let [af (if (< f 0) 0 f) | |
inc-t (inc t) | |
at (if (>= (count v) inc-t) inc-t (count v))] | |
(subvec v af at))) | |
mutate-cell (fn [board r c acc-board] | |
(let [cell ((board r) c) | |
hor-zone (align-subvec board (dec r) (inc r)) | |
zone (mapcat #(align-subvec % (dec c) (inc c)) hor-zone) | |
live-cells-count (count (filter live-cell? zone)) | |
live-neibs (if (live-cell? cell) (dec live-cells-count) live-cells-count) | |
mutated-cell (transit-cell cell live-neibs)] | |
(assoc acc-board r (assoc (acc-board r) c mutated-cell))))] | |
(let [vec-board (vec (map vec board)) | |
rc (count board) | |
cc (count (first board))] | |
(loop [r 0 c 0 acc-board vec-board] | |
(let [next-board (mutate-cell vec-board r c acc-board)] | |
(cond | |
(> cc (inc c)) (recur r (inc c) next-board) | |
(> rc (inc r)) (recur (inc r) 0 next-board) | |
:else (map #(apply str %) next-board))))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment