-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathday14.clj
34 lines (28 loc) · 1.24 KB
/
day14.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
(ns advent-2021-clojure.day14
(:require [advent-2021-clojure.utils :as u]))
(defn parse-input [input]
(let [[template rules] (u/split-blank-line input)]
[template
(->> (re-seq #"\w+" rules) (partition 2) (map vec) (into {}))]))
(defn update-add [m k n] (update m k #(+ (or % 0) n)))
(defn apply-rules [rules freqs]
(reduce (fn [acc [[a b :as word] n]] (let [c (rules word)]
(-> acc
(update-add (str a c) n)
(update-add (str c b) n))))
{} freqs))
(defn score [initial-template freqs]
(let [char-freqs (reduce (fn [acc [[a] n]] (update-add acc a n))
{(last initial-template) 1}
freqs)
sorted-instances (sort-by - (vals char-freqs))]
(apply - ((juxt first last) sorted-instances))))
(defn solve [input step]
(let [[template rules] (parse-input input)
initial-freqs (->> template (partition 2 1) (map (partial apply str)) frequencies)]
(->> (iterate (partial apply-rules rules) initial-freqs)
(drop step)
first
(score template))))
(defn part1 [input] (solve input 10))
(defn part2 [input] (solve input 40))