-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday5.clj
53 lines (43 loc) · 1.44 KB
/
day5.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
(ns day5)
(def polymer (butlast (slurp "day5.txt")))
;; Part One
(defn reduce-start
"Reduce the start of the polymer until it cannot."
[polymer]
(loop [[first second & rest :as polymer] polymer]
(when first
(if (and second (= 32 (Math/abs (- (int second) (int first)))))
(recur rest)
polymer))))
(defn reduce-polymer
"Reduce the polymer."
[polymer]
(loop [polymer polymer
reduced '()]
(if-let [start-reduced (reduce-start polymer)]
(if (or (empty? reduced)
(= start-reduced polymer))
;; we did not reduce the polymer or we're just starting
;; => continue to the next character
(recur (rest start-reduced)
(conj reduced (first start-reduced)))
;; we reduced the polymer
;; => backtrack of 1 character in case the reduction cascades
(recur (conj start-reduced (first reduced))
(rest reduced)))
(apply str (reverse reduced)))))
(assert (= "dabCBAcaDA"
(reduce-polymer (seq "dabAcCaCBAcCcaDA"))))
(count polymer)
(time (count (reduce-polymer polymer)))
;; Part Two
(def unit
(->> (range 65 91)
(map #(set [(char %) (char (+ % 32))]))
(apply min-key (fn [unit]
(->> polymer
(remove unit)
reduce-polymer
count)))
time))
(count (reduce-polymer (remove unit polymer)))