-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday15.clj
73 lines (57 loc) · 1.71 KB
/
day15.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
(ns day15
(:require aoc))
(defn find-radius [[sx sy bx by]]
[[sx sy] (aoc/manhattan [sx sy] [bx by])])
(defn seen-in-row [sensors row]
(->> sensors
(mapcat (fn [[[sx sy] r]]
(let [diff (- r (abs (- row sy)))]
(when (pos? diff)
[(- sx diff) (+ sx diff)]))))
(remove nil?)
sort
vec))
(defn part-1 [sensors row]
(let [seen (seen-in-row sensors row)]
(- (peek seen) (first seen))))
(defn find-coeffs [[[sx sy] r]]
[[(+ (- sy sx) (inc r))
(- (- sy sx) (inc r))]
[(+ (+ sy sx) (inc r))
(- (+ sy sx) (inc r))]])
(defn extract-useful [coeffs a-or-b]
(->> coeffs
(mapcat a-or-b)
frequencies
(filter #(> (val %) 1))
keys))
(defn found-beacon? [sensors location]
(not-any?
(fn [[sensor r]]
(<= (aoc/manhattan sensor location) r))
sensors))
(defn calc-score [[col row]]
(+ (* 4000000 col) row))
(defn part-2 [sensors limit]
(let [coeffs (map find-coeffs sensors)
pos-coeffs (extract-useful coeffs first)
neg-coeffs (extract-useful coeffs second)
potential-locations
(for [a pos-coeffs
b neg-coeffs
:when (and (> b a) (zero? (mod (- b a) 2)))
:let [x (/ (- b a) 2)
y (/ (+ b a) 2)]
:when (and (< 0 x limit) (< 0 y limit))]
[x y])]
(->> potential-locations
(aoc/find-first #(found-beacon? sensors %))
calc-score)))
(defn solve
([] (solve (aoc/read-file 15)))
([input]
(let [limit 4000000
sensors (aoc/parse-input input (comp find-radius aoc/integers))]
[(part-1 sensors (/ limit 2))
(part-2 sensors limit)])))
(solve)