/
day08.clj
71 lines (61 loc) · 1.73 KB
/
day08.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
(ns day08
(:require
[clojure.core.matrix :as matrix]
[aoc.core :refer [read-input-lines map-all]]
[medley.core :as m]))
(defn to-grid
"Parse a two-dimensional grid of single digit numbers into a map structure.
The keys are the [x y] coordinates and the values are the value at that coord
The top left is [0 0]. The bottom right is [col-n row-n].
"
[raw]
(->>
(map-indexed (fn [y line]
(map-indexed (fn [x char]
[x y (parse-long (str char))]) line)) raw)
(reduce (fn [g row]
(reduce (fn [g [x y v]]
(assoc g [x y] v)) g row)) {})))
(def compass {:north [0 -1]
:east [1 0]
:south [0 1]
:west [-1 0]})
(defn neighbors
"Get all neigbors of pos in a direction"
[g pos dir]
(->> pos
(iterate #(matrix/add % dir))
rest
(map g)
(take-while some?)))
(defn visible? [grid coord]
(->> (vals compass)
(map #(neighbors grid coord %))
(map (fn [neighbors] (every? #(< % (get grid coord)) neighbors)))
(some true?)))
(defn part1 [fname]
(let [g (to-grid (read-input-lines fname))]
(->> (keys g)
(map #(visible? g %))
(filter true?)
(count))))
(defn scenic-score [grid coord]
(->> (vals compass)
(map #(neighbors grid coord %))
(map-all #(< % (get grid coord)))
(map #(m/take-upto false? %))
(map count)
(apply *)))
(defn part2 [fname]
(let [g (to-grid (read-input-lines fname))]
(->> (keys g)
(map #(scenic-score g %))
(apply max))))
(part1 "day08-sample.txt")
;; => 21
(part1 "day08.txt")
;; => 1807
(part2 "day08-sample.txt")
;; => 8
(part2 "day08.txt")
;; => 480000