summaryrefslogtreecommitdiffstats
path: root/day09.lisp
diff options
context:
space:
mode:
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