Permalink
Browse files

Game of Life

  • Loading branch information...
1 parent 46148ef commit b7d163d6b917c618cd94be9c650de4fd91beaf16 Andrey Paramonov committed Dec 9, 2012
Showing with 33 additions and 0 deletions.
  1. +17 −0 src/dojo/life.clj
  2. +16 −0 test/dojo/life_test.clj
View
@@ -0,0 +1,17 @@
+;; http://en.wikipedia.org/wiki/Conway's_Game_of_Life
+;;
+;; Inspired at Global Day of Code Retreat 2012, Toronto
+
+(ns dojo.life)
+
+; http://rosettacode.org/wiki/Conway's_Game_of_Life#Clojure
+
+(defn neighbours [[x y]]
+ (for [dx [-1 0 1] dy [-1 0 1]
+ :when (not (and (zero? dx) (zero? dy)))]
+ [(+ x dx) (+ y dy)]))
+
+(defn next-step [cells]
+ (set (for [[cell n] (frequencies (mapcat neighbours cells))
+ :when (or (= n 3) (and (= n 2) (some #{cell} cells)))]
+ cell)))
@@ -0,0 +1,16 @@
+(ns dojo.life-test
+ (:use clojure.test dojo.life))
+
+(deftest neighbours-test
+ (is (= [[1 1] [1 2] [1 3] [2 1] [2 3] [3 1] [3 2] [3 3]]
+ (neighbours [2 2]))))
+
+(deftest blinker-test
+ (is (= #{[2 3] [3 3] [4 3]}
+ (next-step #{[3 2] [3 3] [3 4]})))
+ (is (= #{[3 2] [3 3] [3 4]}
+ (next-step #{[2 3] [3 3] [4 3]}))))
+
+(deftest beehive-test
+ (is (= #{[3 2] [2 3] [2 4] [3 5] [4 4] [4 3]}
+ (next-step #{[3 2] [2 3] [2 4] [3 5] [4 4] [4 3]}))))

0 comments on commit b7d163d

Please sign in to comment.