Last active
August 16, 2016 22:11
-
-
Save reborg/09752a1409688365541bda89489d2c6f to your computer and use it in GitHub Desktop.
Game of life Clojure
This file contains 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 count-neighbors [h w x y cells] | |
(->> (for [dx [-1 0 1] | |
dy [-1 0 1] | |
:let [x' (+ x dx) | |
y' (+ y dy)] | |
:when (and (not (= dx dy 0)) | |
(<= 0 x' (dec w)) | |
(<= 0 y' (dec h)))] [x' y']) | |
(filter cells) | |
count)) | |
(defn under? [n alive?] (and (< n 2) alive?)) | |
(defn healthy? [n alive?] (or (and alive? (= n 2)) (= n 3))) | |
(defn over? [n alive?] (and (> n 3) alive?)) | |
(defn reproduce? [n alive?] (and (= n 3) (not alive?))) | |
(defn apply-rules [h w x y cells] | |
(let [n (count-neighbors h w x y cells) | |
alive (contains? cells [x y]) | |
should-live (or (healthy? n alive) (reproduce? n alive)) | |
should-die (or (under? n alive) (over? n alive))] | |
(and should-live (not should-die)))) | |
(defn next-gen [h w cells] | |
(into #{} | |
(for [x (range 0 w) | |
y (range 0 h) | |
:when (apply-rules h w x y cells)] [x y]))) | |
;; blinker: (next-gen 5 5 #{[2 1] [2 2] [2 3]}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment