Last active
December 29, 2016 22:27
-
-
Save nukemberg/e382f7bb0375089e9a06e65736a3f5c8 to your computer and use it in GitHub Desktop.
Conway's Game of Life in Clojure
This file contains 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 conway.core | |
(:require [clojure.set :refer [intersection]])) | |
(defn neighbours [[x y]] | |
(for [i [-1 0 1] j [-1 0 1] :when (not= i j 0)] | |
[(x + i) (y + j)])) | |
(defn alive-next-gen [board cell] | |
(let [alive-neighbours (intersection board (neighbours cell)) | |
alive (board cell)] | |
(cond | |
(and alive (< alive-neighbours 2)) false ; underpopulation | |
(and alive (= 2 alive-neighbours)) true | |
(and alive (> alive-neighbours 3)) ; overpopulation | |
(= 3 alive-neighbours) true ; birth | |
false | |
))) | |
(defn game [board] | |
(let [board-neighbours (map neighbours board)] | |
(filter (partial alive-next-gen board) board-neighbours))) | |
; board is a set of cells, e.g.: #{[1 0] [2 3]} |
This file contains 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 conway.core-test | |
(:require [clojure.test :refer :all] | |
[conway.core :refer :all])) | |
(deftest board-test | |
(testing "blinker" | |
(let [board #{[1 0] [1 1] [1 2]}] | |
(is (game board) #{[1 1] [2 1] [0 1]}) | |
(is (game (game board)) board))) | |
(testing "block" | |
(let [board #{[0 1] [1 1] [1 0] [0 0]}] | |
(is (game board) board)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment