Skip to content

Instantly share code, notes, and snippets.

@jmgimeno
Created January 9, 2012 12:36
Show Gist options
  • Save jmgimeno/1582758 to your computer and use it in GitHub Desktop.
Save jmgimeno/1582758 to your computer and use it in GitHub Desktop.
Conway's Game of Life
; From: http://clj-me.cgrand.net/2011/08/19/conways-game-of-life/
(defn neighbours [[x y]]
(for [dx [-1 0 1] dy (if (zero? dx) [-1 1] [-1 0 1])]
[(+ dx x) (+ dy y)]))
(defn step [cells]
(set (for [[loc n] (frequencies (mapcat neighbours cells))
:when (or (= n 3) (and (= n 2) (cells loc)))]
loc)))
Let’s see how it behaves with the “blinker” configuration:
(def board #{[1 0] [1 1] [1 2]})
; #'user/board
(take 5 (iterate step board))
; (#{[1 0] [1 1] [1 2]} #{[2 1] [1 1] [0 1]} #{[1 0] [1 1] [1 2]} #{[2 1] [1 1] [0 1]} #{[1 0] [1 1] [1 2]})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment