-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday12.clj
54 lines (42 loc) · 1.47 KB
/
day12.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
54
(ns day12
(:require aoc
[clojure.string :as str]))
(def cache (atom {}))
(def is-operational? #{\. \?})
(def is-damaged? #{\# \?})
(defn parse-line [line]
(let [[pattern groups] (str/split line #" ")]
[pattern (aoc/integers groups)]))
(defn unfold [[patts groups]]
[(->> patts
(repeat 5)
(str/join "?"))
(->> groups
(repeat 5)
flatten)])
(defn arrangements [[pattern groups :as pg]]
(if-let [res (@cache pg)]
res
(if (empty? groups)
(if (every? is-operational? pattern) 1 0)
(let [[size & tl] groups
post (+ (reduce + tl) (count tl))
score (atom 0)]
(doseq [pre (range (inc (- (count pattern) post size)))
:let [[before pattern'] (split-at pre pattern)
[current remaining] (split-at size pattern')]
:while (every? is-operational? before)
:when (every? is-damaged? current)]
(cond
(empty? tl) (when (every? is-operational? remaining)
(swap! score inc))
(is-operational? (first remaining))
(swap! score + (arrangements [(rest remaining) tl]))))
(swap! cache assoc pg @score)
@score))))
(defn solve [input]
(let [lines (aoc/parse-input input parse-line)
unfolded (map unfold lines)]
[(aoc/sum-map arrangements lines)
(aoc/sum-pmap arrangements unfolded)]))
(solve (aoc/read-file 12))