You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
39 lines
1.4 KiB
Clojure
39 lines
1.4 KiB
Clojure
3 years ago
|
(require '[clojure.string :as str])
|
||
|
|
||
3 years ago
|
(def input (->> (slurp "./in")
|
||
3 years ago
|
str/split-lines
|
||
|
((juxt
|
||
3 years ago
|
#(let [init-polymer (first %)]
|
||
|
(for [i (range 0 (dec (count init-polymer)))]
|
||
|
(subs init-polymer i (+ i 2))))
|
||
3 years ago
|
(fn [lines]
|
||
|
(->> lines
|
||
|
(drop 2)
|
||
|
(map #(str/split % #" -> "))
|
||
3 years ago
|
(map (fn [[[a b] c]]
|
||
|
{(str/join [a b]) (map str/join [[a c] [c b]])}))
|
||
3 years ago
|
(reduce into)
|
||
3 years ago
|
))))))
|
||
|
|
||
3 years ago
|
(def blank-map (zipmap (keys (second input)) (repeat 0)))
|
||
3 years ago
|
|
||
|
(defn grow-polymer [polymer insertion-rules]
|
||
|
(reduce
|
||
3 years ago
|
#(let [[p1 p2] (insertion-rules (key %2)) v (val %2)]
|
||
|
(-> %1 (update p1 + v) (update p2 + v)))
|
||
3 years ago
|
blank-map
|
||
3 years ago
|
(filter (comp pos? val) polymer)))
|
||
3 years ago
|
|
||
3 years ago
|
(def growth-seq
|
||
3 years ago
|
(iterate #(grow-polymer % (second input))
|
||
|
(reduce #(update %1 %2 inc) blank-map (first input))))
|
||
3 years ago
|
|
||
3 years ago
|
(let [final-polymer (nth growth-seq 40)
|
||
|
letter-counts (reduce
|
||
|
(fn [r [k v]] (-> r (update (first k) + v) (update (second k) + v)))
|
||
|
(zipmap (str/join (keys final-polymer)) (repeat 0))
|
||
|
final-polymer)
|
||
|
unique-counts (filter pos? (map #(Math/ceil (/ (val %) 2)) letter-counts))]
|
||
|
(println (- (apply max unique-counts) (apply min unique-counts))))
|
||
3 years ago
|
|