Skip to content

Instantly share code, notes, and snippets.

@joejag
Created December 17, 2011 12:01
Show Gist options
  • Save joejag/1490048 to your computer and use it in GitHub Desktop.
Save joejag/1490048 to your computer and use it in GitHub Desktop.
Conways Game of Life with Paul Wilson at Glasgow Code Retreat
(ns coderetreat.conway3
(:use clojure.test clojure.contrib.pprint)
)
; world is a set of live cells
; find all the neighbours of live cells in the world
; find the frequencies of this big list. i.e. [1 1] 4 // 1,1 has 4 neighbours
; reduce with conway rules, (2 & 3 survives), (3 and dead becomes alive)
; take first element from list (the cell reference)
(defn neighbours-of [[x y]]
[[(dec x) (inc y)] [x (inc y)] [(inc x) (inc y)]
[(dec x) y] [(inc x) y]
[(dec x) (dec y)] [x (dec y)] [(inc x) (dec y)]]
)
(defn neighbour-frequencies [world] (frequencies (mapcat neighbours-of world)))
(defn survives? [neighbours-count is-alive]
(or
(and (true? is-alive) (or (= 2 neighbours-count) (= 3 neighbours-count)))
(and (false? is-alive) (= 3 neighbours-count))
)
)
(defn evolve [world]
(set
(map first
(filter #(survives? (second %) (contains? world (first %)))
(neighbour-frequencies world)))))
(def world #{[0 1] [1 1] [2 1]})
(pprint (take 5 (iterate evolve world)))
; prints out
; (#{[2 1] [1 1] [0 1]}
; #{[1 0] [1 1] [1 2]}
; #{[2 1] [1 1] [0 1]}
; #{[1 0] [1 1] [1 2]}
; #{[2 1] [1 1] [0 1]})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment