advent-of-code-2024

My solutions to AoC 2024
Log | Files | Refs

commit 61dc14d111cb4b73cde23efd139874acc1146f37
parent eba1e3d671fb248cdf9966ced55805a490815e97
Author: Lukas Henkel <lh@entf.net>
Date:   Thu,  5 Dec 2024 07:06:24 +0100

Simplify

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

diff --git a/src/day-5.lisp b/src/day-5.lisp @@ -12,17 +12,6 @@ #'parse-integer (uiop:split-string line :separator '(#\,)))) -(defun update-ordered-p (update rules) - (loop for (first second) in rules - for pos-first = (position first update) - for pos-second = (position second update) - unless (or - (null pos-first) - (null pos-second) - (< pos-first pos-second)) - do (return nil) - finally (return t))) - (defun order-update (update rule-map) (sort update (lambda (first second) (not (gethash (list second first) rule-map))))) @@ -31,8 +20,7 @@ (aref update (floor (length update) 2))) (defun day-5 (input) - (loop with rules = nil - with rule-map = (make-hash-table :test #'equal) + (loop with rule-map = (make-hash-table :test #'equal) with processing-updates = nil with task-1 = 0 with task-2 = 0 @@ -40,15 +28,13 @@ until (null line) do (cond (processing-updates - (let ((update (parse-update line))) - (if (update-ordered-p update rules) - (incf task-1 (middle-page-number update)) - (progn - (setf update (order-update update rule-map)) - (incf task-2 (middle-page-number update)))))) + (let* ((update (parse-update line)) + (sorted (order-update (copy-seq update) rule-map)) + (middle (middle-page-number sorted))) + (if (seq= update sorted) + (incf task-1 middle) + (incf task-2 middle)))) ((string= line "") (setf processing-updates t)) - (t (let ((rule (parse-rule line))) - (setf (gethash rule rule-map) t) - (push rule rules)))) + (t (setf (gethash (parse-rule line) rule-map) t))) finally (return (values task-1 task-2))))