Skip to content

Instantly share code, notes, and snippets.

@mariussoutier
Created November 18, 2011 08:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mariussoutier/1375948 to your computer and use it in GitHub Desktop.
Save mariussoutier/1375948 to your computer and use it in GitHub Desktop.
Conway's Game of Life in Clojure
;;; Conway's Game of Life
;;; Using a set of coordinates to provide a infinite world
;;;
;;; Moritz Ulrich <ulrich.moritz@googlemail.com>
;;; Cologne Clojure User Group
;;; November 17, 2011
(ns game-of-life.core
(:use [clojure.set :as set]))
(defrecord Coord [x y])
(defn coord [x y] (Coord. x y))
(defn neighbors [world c]
(let [deltas [[1 0]
[1 1]
[0 1]
[-1 0]
[0 -1]
[-1 1]
[1 -1]
[-1 -1]]]
(map (fn [[x y]] (make-coord
(+ x (:x c)) (+ y (:y c)))) deltas)))
(defn neighbor-count [world c]
(count (keep #(get world %) (neighbors world c))))
(defn dies? [world c]
(let [x (neighbor-count world c)]
(or (< x 2)
(> x 3))))
(defn survives? [world c]
(<= 2 (neighbor-count world c) 3))
(defn reborn? [world c]
(= 3 (neighbor-count world c)))
(defn reborn-helper
"Returns a set containing all coordinates we need to check for birth"
[world]
(reduce set/union (map (partial neighbors world) world)))
(defn next-generation [world]
(set/union (set (remove (partial dies? world) world))
(set (filter (partial reborn? world) (reborn-helper world)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment