Created
November 18, 2011 08:54
-
-
Save mariussoutier/1375948 to your computer and use it in GitHub Desktop.
Conway's Game of Life in Clojure
This file contains hidden or 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
;;; Conway's Game of Life | |
;;; Using a set of coordinates to provide a infinite world | |
;;; | |
;;; Moritz Ulrich <[email protected]> | |
;;; 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