Skip to content

Instantly share code, notes, and snippets.

@skuro
Created January 13, 2016 19:53
Show Gist options
  • Select an option

  • Save skuro/fa5f3300acfec30b0797 to your computer and use it in GitHub Desktop.

Select an option

Save skuro/fa5f3300acfec30b0797 to your computer and use it in GitHub Desktop.
#amsclj 73
(ns life.core
(:require [clojure.pprint :as pp]))
(def grid [[:alive :dead :alive]
[:dead :dead :dead]
[:alive :alive :alive]])
(defn cell
"Returns the value of the cell at the given coordinates"
[grid [x y]]
((grid x) y))
(defn neighbours
"Find the neighbouring cells of the given cell"
[grid [x y]]
(for [dx (range (dec x) (+ 2 x))
dy (range (dec y) (+ 2 y))
:when (and (<= 0 dx)
(<= 0 dy)
(< dx (count grid))
(< dy (count (first grid)))
(not (= [x y] [dy dx])))]
(cell grid [dx dy])))
(defn alive-neighbours
"Find the alive neigbours of the given cell"
[grid [x y]]
(count (filter (partial = :alive) (neighbours grid [x y]))))
(defn next-state
"Yields next life state of given coordinates"
[grid [x y]]
(let [current (cell grid [x y])
live-neighbours (alive-neighbours grid [x y])]
(if (and (= current :alive) (< live-neighbours 2)) :dead
(if (and (= current :alive) (#{2 3} live-neighbours)) :alive
(if (and (= current :alive) (> live-neighbours 3)) :dead
(if (and (= current :dead) (= live-neighbours 3)) :alive current))))))
(defn next-row
"Calculates the next states for a grid row"
[grid row]
(let [coords (map (fn [x] [row x]) (range 0 (count (first grid))))]
(mapv (partial next-state grid) coords)))
(defn next-grid
"Yields next grid given a grid"
[grid]
(mapv (fn [row] (next-row grid row)) (range 0 (count grid))))
(defn print-grid
"Prints the grid as a real grid"
[grid]
(println "-------------------------")
(doall (map println grid))
(println "-------------------------"))
(defn play
"Shows how the grid evolves until it's stable"
[grid]
(print-grid grid)
(let [current grid
next (next-grid grid)]
(if (= current next)
:done
(do (Thread/sleep 1000)
(recur next)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment