Skip to content

Instantly share code, notes, and snippets.

@MattRoelle
Created September 2, 2021 15:51
Show Gist options
  • Save MattRoelle/e21bfb30f49f731dce9c761d050ab643 to your computer and use it in GitHub Desktop.
Save MattRoelle/e21bfb30f49f731dce9c761d050ab643 to your computer and use it in GitHub Desktop.
(def start-grid [[0 0 0 0 0 1 0 0 0 0]
[0 0 0 0 1 0 0 0 0 0]
[0 0 0 0 1 0 0 0 1 0]
[0 0 0 0 0 0 0 0 1 0]
[0 0 0 0 0 0 0 0 1 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 1 1 0 0 0]
[0 0 1 0 0 1 1 0 0 0]
[0 1 0 0 0 0 0 0 0 0]
[1 0 0 0 0 0 0 0 0 0]])
(def neighbors [[-1 -1]
[-1 0]
[-1 1]
[0 -1]
[0 1]
[1 -1]
[1 0]
[1 1]])
(defn format-row [row] (clojure.string/join "" (map (fn [cell] (if (= cell 1) "◼" "◻")) row)))
(defn format-grid [world] (clojure.string/join "\n" (map format-row world)))
(defn print-grid [grid]
(println (clojure.string/join "" (repeat (count (first grid)) "-")))
(println (format-grid grid))
grid)
(defn map-grid [grid l]
(let [w (count (first grid)) h (count grid)]
(mapv (fn [y]
(mapv (fn [x]
(l grid x y))
(range 0 w))) (range 0 h))))
(defn get-cell [grid x y] (get (get grid y []) x 0))
(defn neighbor-count [grid x y]
(reduce + (map
(fn [n] (get-cell grid (+ x (get n 0)) (+ y (get n 1))))
neighbors)))
(defn rules [c n]
(if (= c 1)
(cond (< n 2) 0 (< n 4) 1 :else 0)
(if (= n 3) 1 0)))
(defn tick [grid]
(map-grid grid
(fn [grid x y]
(rules (get-cell grid x y) (neighbor-count grid x y)))))
(->> start-grid
print-grid
tick
print-grid
tick
print-grid
tick
print-grid
tick
print-grid)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment