From 0318719d8bfa18314707da50e799f2455ae7cca8 Mon Sep 17 00:00:00 2001 From: Alexandre Jesus Date: Wed, 20 Dec 2023 21:24:48 +0000 Subject: day09 --- day09.lisp | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 day09.lisp (limited to 'day09.lisp') 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 -- cgit v1.2.3