day14: clean up part2

master
Clyne 3 years ago
parent bd674ed712
commit 1faa513087

@ -1,52 +1,40 @@
(require '[clojure.string :as str]) (require '[clojure.string :as str])
(def input (->> (slurp "./in2") (def input (->> (slurp "./in")
str/split-lines str/split-lines
((juxt ((juxt
first #(let [init-polymer (first %)]
(for [i (range 0 (dec (count init-polymer)))]
(subs init-polymer i (+ i 2))))
(fn [lines] (fn [lines]
(->> lines (->> lines
(drop 2) (drop 2)
(map #(str/split % #" -> ")) (map #(str/split % #" -> "))
(flatten) (map (fn [[pair ltr]]
(apply (partial assoc {})) {pair (map str/join [[(first pair) ltr] [ltr (second pair)]])}))
(reduce into)
)))))) ))))))
(def blank-map (def blank-map (zipmap (keys (second input)) (repeat 0)))
(reduce
#(assoc %1 %2 0)
{}
(keys (second input))))
(defn grow-polymer [polymer insertion-rules] (defn grow-polymer [polymer insertion-rules]
(reduce (reduce
(fn [res pair] #(let [[p1 p2] (insertion-rules (key %2)) v (val %2)]
(let [pk (key pair) (-> %1 (update p1 + v) (update p2 + v)))
p1 (str/join [(first pk) (insertion-rules pk)])
p2 (str/join [(insertion-rules pk) (second pk)])]
(-> res (update p1 + (val pair)) (update p2 + (val pair)))
))
blank-map blank-map
(filter #(pos? (val %)) polymer) (filter (comp pos? val) polymer)))
))
(def growth-seq (def growth-seq
(iterate (iterate #(grow-polymer % (second input))
#(grow-polymer % (second input)) (reduce #(update %1 %2 inc) blank-map (first input))))
(reduce
#(update %1 %2 inc)
blank-map
(for [i (range 0 (dec (count (first input))))]
(subs (first input) i (+ i 2))))))
(let [results (let [polymer (nth growth-seq 40)
results (filter pos?
(map #(Math/ceil (/ % 2)) (map #(Math/ceil (/ % 2))
(vals (vals
(reduce (reduce
(fn [r p] (-> r #(let [k (key %2) v (val %2)] (-> %1 (update (first k) + v) (update (second k) + v)))
(update (first (key p)) #(if (nil? %) (val p) (+ % (val p)))) (zipmap (flatten (map (partial split-at 1) (keys polymer))) (repeat 0))
(update (second (key p)) #(if (nil? %) (val p) (+ % (val p)))))) polymer))))]
{}
(nth growth-seq 40))))]
(println (- (apply max results) (apply min results)))) (println (- (apply max results) (apply min results))))

Loading…
Cancel
Save