blob: 46374719a95ad160ea9481207f07f812d95f46cd (
plain) (
blame)
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
|
(defstruct problem reports)
(defun parse-integers (string &key (start 0))
(loop for i = start then (cadr o)
as o = (multiple-value-list (parse-integer string :start i :junk-allowed t))
as n = (car o)
while n
collect n))
(defun parse-reports (stream)
(loop for line = (read-line stream nil)
while line
collect (parse-integers line)))
(defun parse-problem (filespec)
(with-open-file (stream filespec)
(make-problem :reports (parse-reports stream))))
(defun report-next-level (report)
(loop for i in (cdr report)
for j in report
collect (- i j)))
(defun report-next-value (report)
(if (every (lambda (v) (= v 0)) report)
0
(+ (car (last report)) (report-next-value (report-next-level report)))))
(defun solve1 (filespec)
(let ((problem (parse-problem filespec)))
(reduce #'+ (mapcar #'report-next-value (problem-reports problem)))))
(defun solve2 (filespec)
(let ((problem (parse-problem filespec)))
(reduce #'+ (mapcar #'report-next-value
(mapcar #'reverse (problem-reports problem))))))
(print (solve1 "data/09/example.txt")) ;; 114
(print (solve1 "data/09/input.txt")) ;; 1916822650
(print (solve2 "data/09/example.txt")) ;; 2
(print (solve2 "data/09/input.txt")) ;; 966
|