Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (ns life.core
- (defn blend [colors]
- (map #(math/round (float (/ (reduce + %) (count colors))))
- (apply map vector colors)))
- (defn moore-neighborhood
- [{:keys [x y]}]
- (let [x-- (dec x)
- x++ (inc x)
- y-- (dec y)
- y++ (inc y)]
- [{:x x-- :y y--} {:x x :y y--} {:x x++ :y y--}
- {:x x-- :y y} {:x x++ :y y}
- {:x x-- :y y++} {:x x :y y++} {:x x++ :y y++}]))
- (defn generate-new-gen [field]
- (let [freq-set (frequencies (apply concat (map moore-neighborhood (keys field))))]
- (into {}
- (remove nil?
- (map (fn [[coord neighbors-count]]
- (case neighbors-count
- 3 {coord (vec (blend (remove nil? (map (partial get field) (moore-neighborhood coord)))))}
- 2 (when (field coord) {coord (field coord)})
- nil))
- freq-set)))))
- (defn cells->str [cells]
- (let [coord-set (keys cells)
- Ys (map :y coord-set)
- Xs (map :x coord-set)]
- (str/join
- \newline
- (map (partial str/join \space)
- (for [y (range (apply min Ys) (inc (apply max Ys)))]
- (for [x (range (apply min Xs) (inc (apply max Xs)))]
- (get cells {:x x :y y} [0 0 0])))))))
- (defn run-life [num-steps cells-set]
- (loop [s num-steps
- cells cells-set]
- (println (cells->str cells) "\n")
- (when (< 0 s)
- (recur (dec s) (generate-new-gen cells)))))
- (def blinker {{:x 0 :y 1} [255 0 0], {:x 1 :y 1} [0 255 0], {:x 2 :y 1} [0 0 255]})
- (run-life 16 blinker)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement