Last active
January 3, 2016 15:49
-
-
Save aleksxor/8485683 to your computer and use it in GitHub Desktop.
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
(ns simple-life.core | |
"Simplified game of life. Random universe consists of ones and | |
zeros. For every iteration we calculate current cell value | |
depending on it's own value and values of it's left and right | |
neighbours. When exactly one of those cells is 1 the resulting | |
value for next generation is 1, otherwise it's 0. For edge | |
elements the absent neighbour counts as 0.") | |
(defn next-cell [coll] | |
"takes collection and returns 1 only if one of collection's | |
elements equals 1" | |
(if (= 1 (reduce + coll)) | |
1 | |
0)) | |
(defn next-gen [coll] | |
"takes collection and expands it's left and right edges with | |
zeros to avoid edge checking. then partitions it by 3 elements | |
with step of 1. then maps it with next-cell function. ie. | |
initial collection: (0 1 1 0) | |
expanded: (0 0 1 1 0 0) | |
partitioned: ((0 0 1) (0 1 1) (1 1 0) (1 0 0)) | |
result: (1 0 0 1) | |
" | |
(map next-cell (partition 3 1 (concat '(0) coll '(0))))) | |
(defn age [num-gens universe] | |
(def u (atom universe)) | |
(dotimes [n num-gens] | |
(swap! u next-gen)) | |
(deref u)) | |
(defn universe [num-cells] | |
"generates random universe consisting of ones and zeros with | |
num-cells length" | |
(take num-cells (repeatedly #(rand-int 2)))) | |
(println (age 30 (universe 40))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment