Advertisement
_eremec_

Untitled

Feb 15th, 2017
411
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (ns life.core
  2.  
  3. (defn blend [colors]
  4.   (map #(math/round (float (/ (reduce + %) (count colors))))
  5.        (apply map vector colors)))
  6.  
  7. (defn moore-neighborhood
  8.   [{:keys [x y]}]
  9.   (let [x-- (dec x)
  10.         x++ (inc x)
  11.         y-- (dec y)
  12.         y++ (inc y)]
  13.     [{:x x-- :y y--} {:x x :y y--} {:x x++ :y y--}
  14.      {:x x-- :y y} {:x x++ :y y}
  15.      {:x x-- :y y++} {:x x :y y++} {:x x++ :y y++}]))
  16.  
  17. (defn generate-new-gen [field]
  18.   (let [freq-set (frequencies (apply concat (map moore-neighborhood (keys field))))]
  19.     (into {}
  20.       (remove nil?
  21.         (map (fn [[coord neighbors-count]]
  22.               (case neighbors-count
  23.                  3 {coord (vec (blend (remove nil? (map (partial get field) (moore-neighborhood coord)))))}
  24.                  2 (when (field coord) {coord (field coord)})
  25.                  nil))
  26.             freq-set)))))
  27.  
  28. (defn cells->str [cells]
  29.   (let [coord-set (keys cells)
  30.         Ys (map :y coord-set)
  31.         Xs (map :x coord-set)]
  32.     (str/join
  33.       \newline
  34.       (map (partial str/join \space)
  35.            (for [y (range (apply min Ys) (inc (apply max Ys)))]
  36.              (for [x (range (apply min Xs) (inc (apply max Xs)))]
  37.                (get cells {:x x :y y} [0 0 0])))))))
  38.  
  39. (defn run-life [num-steps cells-set]
  40.   (loop [s num-steps
  41.          cells cells-set]
  42.     (println (cells->str cells) "\n")
  43.     (when (< 0 s)
  44.       (recur (dec s) (generate-new-gen cells)))))
  45.  
  46. (def blinker {{:x 0 :y 1} [255 0 0], {:x 1 :y 1} [0 255 0], {:x 2 :y 1} [0 0 255]})
  47.  
  48. (run-life 16 blinker)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement