How to resolve the algorithm Conway's Game of Life step by step in the Clojure programming language
How to resolve the algorithm Conway's Game of Life step by step in the Clojure programming language
Table of Contents
Problem Statement
The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton. Conway's game of life is described here: A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells. We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table: Assume cells beyond the boundary are always dead. The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Conway's Game of Life step by step in the Clojure programming language
Source code in the clojure programming language
(defn moore-neighborhood [[x y]]
(for [dx [-1 0 1]
dy [-1 0 1]
:when (not (= [dx dy] [0 0]))]
[(+ x dx) (+ y dy)]))
(defn step [set-of-cells]
(set (for [[cell count] (frequencies (mapcat moore-neighborhood set-of-cells))
:when (or (= 3 count)
(and (= 2 count) (contains? set-of-cells cell)))]
cell)))
(defn print-world
([set-of-cells] (print-world set-of-cells 10))
([set-of-cells world-size]
(let [r (range 0 (+ 1 world-size))]
(pprint (for [y r] (apply str (for [x r] (if (set-of-cells [x y]) \# \.))))))))
(defn run-life [world-size num-steps set-of-cells]
(loop [s num-steps
cells set-of-cells]
(print-world cells world-size)
(when (< 0 s)
(recur (- s 1) (step cells)))))
(def *blinker* #{[1 2] [2 2] [3 2]})
(def *glider* #{[1 0] [2 1] [0 2] [1 2] [2 2]})
You may also check:How to resolve the algorithm Terminal control/Ringing the terminal bell step by step in the Standard ML programming language
You may also check:How to resolve the algorithm Case-sensitivity of identifiers step by step in the Oforth programming language
You may also check:How to resolve the algorithm Variadic function step by step in the COBOL programming language
You may also check:How to resolve the algorithm Mutual recursion step by step in the x86 Assembly programming language
You may also check:How to resolve the algorithm Variable declaration reset step by step in the K programming language