day20: learn futures, arrays

master
Clyne 3 years ago
parent aa5ca3ab7c
commit 15ab28b9ac

@ -1,44 +1,43 @@
(require '[clojure.string :as str]) (require '[clojure.string :as str])
(defn pad-input-map [in-map pad-val] (defn pad-input-map [in-map pad-val]
(let [pad-row (repeat (+ 4 (count (first in-map))) pad-val) (let [ly (count in-map) lx (count (first in-map))
pad-side (repeat 2 pad-val)] sy (+ 4 ly) sx (+ 4 lx)
(mapv vec buffer (byte-array (repeat (* sy sx) pad-val))]
(concat (doseq [y (range 0 ly) x (range 0 lx)]
[pad-row pad-row] (aset-byte buffer (+ (* sx (+ 2 y)) 2 x) (get-in in-map [y x])))
(mapv #(concat pad-side % pad-side) in-map) (mapv vec (partition sx buffer))))
[pad-row pad-row]))))
(defn get-number [in-map y x] (defn get-number [in-map y x]
(concat (subvec (get in-map (dec y)) (dec x) (+ 2 x)) (map (partial get-in in-map)
(subvec (get in-map y) (dec x) (+ 2 x)) [[(dec y) (dec x)] [(dec y) x] [(dec y) (inc x)]
(subvec (get in-map (inc y)) (dec x) (+ 2 x)))) [y (dec x)] [y x] [y (inc x)]
[(inc y) (dec x)] [(inc y) x] [(inc y) (inc x)]]))
(defn get-new-pixel [enhance-algo in-map y x] (defn get-new-pixel [enhance-algo in-map y x]
(->> (get-number in-map y x) (->> (get-number in-map y x)
str/join (reduce #(cond-> (* 2 %1) (= 1 %2) inc) 0)
(#(Integer/parseInt % 2)) (get enhance-algo)))
(get enhance-algo)
{\. 0 \# 1}))
(defn build-output-number-map [enhance-algo in-map] (defn build-output-number-map [enhance-algo in-map]
(let [pad-val (if (= \# (first enhance-algo)) (first (first in-map)) 0) (let [pad-val (if (pos? (first enhance-algo)) (first (first in-map)) 0)
padded-in-map (pad-input-map in-map pad-val)] padded-in-map (pad-input-map in-map pad-val)]
(for [y (range 1 (dec (count padded-in-map)))] (->> (for [y (range 1 (dec (count padded-in-map)))]
(for [x (range 1 (dec (count (first padded-in-map))))] (future
(get-new-pixel enhance-algo padded-in-map y x) (mapv (partial get-new-pixel enhance-algo padded-in-map y)
)))) (range 1 (dec (count (first padded-in-map)))))))
(mapv deref))))
(defn count-lit-pixels [in-map] (defn count-lit-pixels [in-map] ((frequencies (flatten in-map)) 1))
((frequencies (flatten in-map)) 1))
(let [[enhance-algo in-map] (let [[enhance-algo in-map]
(->> (slurp "./in") (->> (slurp "./in")
str/split-lines str/split-lines
((juxt ((juxt (comp (partial mapv {\. 0 \# 1}) first)
first (comp (partial mapv #(mapv {\. 0 \# 1} %)) (partial drop 2)))))
(comp (partial mapv #(mapv {\. 0 \# 1} %))
(partial drop 2)))))
image-output (iterate (partial build-output-number-map enhance-algo) in-map)] image-output (iterate (partial build-output-number-map enhance-algo) in-map)]
(println (count-lit-pixels (nth image-output 50)))) (println "Part 1:" (count-lit-pixels (nth image-output 2)))
(println "Part 2:" (count-lit-pixels (nth image-output 50))))
(shutdown-agents)

Loading…
Cancel
Save