Thursday, 10 December 2015

Conway's Game of Life - my take on it in Clojure

If the board is represented as a vector of strings, where a string represents a row. E.g

[" "
" ## "
" ## "
" ## "
" ## "
" "]
view raw gof_board.clj hosted with ❤ by GitHub
The solution takes the board and returns the it in the next state.

(defn gof
"board is a vector of strings"
[board]
(let [rows (count board)
cols (count (first board))
[living-cell dead-cell] [\# \space]
alive? (fn [[row col]]
(= living-cell (nth (nth board row) col)))
live-neighbours (fn [[row col]]
(for [r [(dec row) row (inc row)]
c [(dec col) col (inc col)]
:when (and (< -1 r) (< r rows)
(< -1 c) (< c cols)
(not= [row col] [r c])
(alive? [r c]))]
[r c]))
next-state (fn [[x y]]
(let [ln (-> [x y] live-neighbours count)
live (if (alive? [x y])
(and (< 1 ln) (< ln 4))
(= 3 ln))]
(if live living-cell dead-cell)))
->row (fn [r] (apply str
(for [c (range cols)] (next-state [r c]))))]
(mapv ->row (range rows))))

No comments :

Post a Comment