aboutsummaryrefslogtreecommitdiffstats
path: root/AoC2023/day09/solver.lisp
diff options
context:
space:
mode:
Diffstat (limited to 'AoC2023/day09/solver.lisp')
-rw-r--r--AoC2023/day09/solver.lisp46
1 files changed, 46 insertions, 0 deletions
diff --git a/AoC2023/day09/solver.lisp b/AoC2023/day09/solver.lisp
new file mode 100644
index 0000000..d515317
--- /dev/null
+++ b/AoC2023/day09/solver.lisp
@@ -0,0 +1,46 @@
+;;03:39
+(ql:quickload '(fiveam arrows transducers))
+(defparameter eg-input "0 3 6 9 12 15
+1 3 6 10 15 21
+10 13 16 21 30 45")
+
+(defun row-reducer (row)
+ (loop for (a b) on row by #'cdr
+ until (null b)
+ collect (- b a)))
+
+(defun terminal-p (row)
+ (every #'zerop row))
+
+(defun forward (row)
+ (if (terminal-p row)
+ 0
+ (+ (forward (row-reducer row)) (car (last row)))))
+
+(defun backward (row)
+ (if (terminal-p row)
+ 0
+ (- (car row) (backward (row-reducer row)))))
+
+(defun solver1 (lines)
+ (arrows:->>
+ lines
+ (mapcar (lambda (line)
+ (forward
+ (mapcar #'parse-integer (uiop:split-string line)))))
+ (apply #'+)))
+
+(defun solver2 (lines)
+ (arrows:->>
+ lines
+ (mapcar (lambda (line)
+ (backward
+ (mapcar #'parse-integer (uiop:split-string line)))))
+ (apply #'+)))
+
+(fiveam:test solutions
+ (fiveam:is (= 114 (solver1 (uiop:split-string eg-input :separator '(#\Newline)))))
+ (fiveam:is (= 2105961943 (solver1 (uiop:read-file-lines "input"))))
+
+ (fiveam:is (= 2 (solver2 (uiop:split-string eg-input :separator '(#\Newline)))))
+ (fiveam:is (= 1019 (solver2 (uiop:read-file-lines "input")))))