Created
December 5, 2011 17:18
-
-
Save wilkes/1434432 to your computer and use it in GitHub Desktop.
Conway using sets
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
(ns conways.core | |
(:use midje.sweet) | |
(:require [clojure.set :as s])) | |
(unfinished ) | |
(def offsets [-1 0 1]) | |
(defn neighbors [[x y]] | |
(s/difference (set (for [x-offset offsets y-offset offsets] | |
[(+ x x-offset) | |
(+ y y-offset)])) | |
#{[x y]})) | |
(fact | |
(neighbors [0 0]) => #{[-1 1] [0 1] [1 1] | |
[-1 0] [1 0] | |
[-1 -1] [0 -1] [1 -1]}) | |
(defn neighbors-satisfy? [cell generation test?] | |
(-> (s/intersection (neighbors cell) | |
generation) | |
count | |
test? | |
boolean)) | |
(defn lives? [cell generation] | |
(neighbors-satisfy? cell generation #(some #{%} [2 3]))) | |
(fact | |
(lives? [0 0] #{[0 0] [1 0] [1 1]}) => true | |
(lives? [0 0] #{[0 0] [1 0] [1 1] [0 1]}) => true | |
(lives? [0 0] #{[0 0] [1 0] [1 1] [0 1] [-1 -1]}) => false) | |
(defn born? [cell generation] | |
(neighbors-satisfy? cell generation #(= 3 %))) | |
(fact | |
(born? [0 0] #{[1 0] [1 1]}) => false | |
(born? [0 0] #{[1 0] [1 1] [0 1]}) => true | |
(born? [0 0] #{[1 0] [1 1] [0 1] [-1 -1]}) => false) | |
(defn survivors [generation] | |
(set (filter #(lives? % generation) generation))) | |
(defn newborns [generation] | |
(set (filter #(born? % generation) | |
(set (mapcat neighbors generation))))) | |
(defn evolve [generation] | |
(s/union (survivors generation) | |
(newborns generation))) | |
(fact | |
(evolve #{[0 0] [1 0] [1 1]}) => #{[1 0] [0 0] [1 1] [0 1]}) | |
(defn first-generation | |
([] | |
(first-generation 10 10 0.5)) | |
([max-x max-y prob] | |
(set (for [x (range max-x) y (range max-y) | |
:when (> (rand) prob)] | |
[x y])))) | |
(defn generations [generation] | |
(let [next-gen (evolve generation)] | |
(lazy-cat (cons next-gen (generations next-gen))))) | |
;; (take 10 (generations (first-generation))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment