summaryrefslogtreecommitdiffstats
path: root/day09.lisp
diff options
context:
space:
mode:
authorAlexandre Jesus <adbjesus@gmail.com>2023-12-20 21:24:48 +0000
committerAlexandre Jesus <adbjesus@gmail.com>2023-12-20 21:24:48 +0000
commit0318719d8bfa18314707da50e799f2455ae7cca8 (patch)
tree0289c4adc886889d8b129284bc2b0010939d8828 /day09.lisp
parent71e1e965a3228c03e4cd5e4b9a609e301779abcb (diff)
downloadaoc2023-0318719d8bfa18314707da50e799f2455ae7cca8.tar.gz
aoc2023-0318719d8bfa18314707da50e799f2455ae7cca8.zip
day09
Diffstat (limited to 'day09.lisp')
-rw-r--r--day09.lisp41
1 files changed, 41 insertions, 0 deletions
diff --git a/day09.lisp b/day09.lisp
new file mode 100644
index 0000000..4637471
--- /dev/null
+++ b/day09.lisp
@@ -0,0 +1,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