blob: 05353f01525621a7a30c3eefc78b155f2e880527 (
plain)
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
|
(ql:quickload '(fiveam uiop arrows))
(defun line-of-sight (direction p width height)
(case direction
(right (loop for l from (1+ p) below (* width (1+ (floor p width))) collect l))
(left (loop for l downfrom (1- p) to (* width (floor p width)) collect l))
(bottom (loop for l from (+ p width) below (* width height) by width collect l))
(top (loop for l downfrom (- p width) to 0 by width collect l))))
(defun forest (data)
(let ((width (length (car data)))
(height (length data)))
(values width height
(map 'vector
(lambda (x) (- (char-code x) 48))
(apply #'concatenate 'string data)))))
(defun solver-p1 (filename)
(multiple-value-bind (width height forest-arr) (forest (uiop:read-file-lines filename))
(loop for base across forest-arr
and p from 0
count (some (lambda (direction)
(loop for l in (line-of-sight direction p width height)
for tree-height = (aref forest-arr l)
always (< tree-height base)))
'(right left top bottom)))))
(defun solver-p2 (filename)
(multiple-value-bind (width height forest-arr) (forest (uiop:read-file-lines filename))
(flet ((score-direction (base dir)
(loop for l in dir
for tree-height = (aref forest-arr l)
count l until (>= tree-height base))))
(loop for base across forest-arr
and p from 0
maximize (arrows:->> '(right left top bottom)
(mapcar (lambda (direction)
(score-direction base (line-of-sight direction p width height))))
(apply #'* ))))))
(fiveam:test solutions
(fiveam:is (= 21 (solver-p1 "eg-in")))
(fiveam:is (= 1672 (solver-p1 "input")))
(fiveam:is (= 8 (solver-p2 "eg-in")))
(fiveam:is (= 327180 (solver-p2 "input"))))
(fiveam:run-all-tests)
|