advent-of-code-2023

My solutions to AoC 2023
git clone git://git.entf.net/advent-of-code-2023
Log | Files | Refs

commit 8d76db913773c02a383f070c9c57bb5b0a491cfc
parent d23cd36cd3c107662e3ba682530ec7350c7b9a71
Author: Lukas Henkel <lh@entf.net>
Date:   Sat,  9 Dec 2023 06:20:41 +0100

Day 9 task 2

Diffstat:
Msrc/day-9.lisp | 22+++++++++++++++++-----
1 file changed, 17 insertions(+), 5 deletions(-)

diff --git a/src/day-9.lisp b/src/day-9.lisp @@ -3,18 +3,30 @@ (:export #:day-9)) (in-package #:aoc/day-9) +(defun diff-sequence (numbers) + (loop with last = (first numbers) + for number in (rest numbers) + collect (- number last) + do (setf last number))) + (defun find-next-value (numbers) - (let ((new-sequence (loop with last = (first numbers) - for number in (rest numbers) - collect (- number last) - do (setf last number)))) + (let ((new-sequence (diff-sequence numbers))) (if (every (curry #'= 0) new-sequence) (first numbers) (+ (lastcar numbers) (find-next-value new-sequence))))) +(defun find-previous-value (numbers) + (let ((new-sequence (diff-sequence numbers))) + (if (every (curry #'= 0) new-sequence) + (first numbers) + (- (first numbers) + (find-previous-value new-sequence))))) + (defun day-9 (input) (loop for line = (read-line input nil) while line for numbers = (read-number-list line) - sum (find-next-value numbers) fixnum)) + sum (find-next-value numbers) into task-1 fixnum + sum (find-previous-value numbers) into task-2 fixnum + finally (return (values task-1 task-2))))