From 80d2d9465204a6f5848430cf2da60c683e6adddb Mon Sep 17 00:00:00 2001 From: Oscar Najera Date: Sun, 17 Dec 2023 08:54:31 +0100 Subject: part2 --- AoC2023/day15/solver.lisp | 37 +++++++++++++++++++++++++++++++++---- 1 file changed, 33 insertions(+), 4 deletions(-) (limited to 'AoC2023') diff --git a/AoC2023/day15/solver.lisp b/AoC2023/day15/solver.lisp index fbcbf77..5bb2599 100644 --- a/AoC2023/day15/solver.lisp +++ b/AoC2023/day15/solver.lisp @@ -1,6 +1,6 @@ ;; 17:04 ;; 17:34 part1 -(ql:quickload '(fiveam str)) +(ql:quickload '(fiveam str arrows)) (defparameter eg-in "rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7") @@ -15,9 +15,38 @@ (str:split "," (str:trim in)) :key #'hash)) +(defun implement-instructions (instructions &aux (boxes (make-array 256 :initial-element nil))) + (cl-ppcre:do-register-groups (label operator (#'parse-integer focal-length)) + ("(\\w+)([=-])(\\d+)?" instructions) + (let ((content + (aref boxes (hash label)))) + (flet ((is-lens (c) (equal (car c) label))) + (arrows:->> + (cond + ((equal "-" operator) + (remove-if #'is-lens content)) + ((equal "=" operator) + (if (zerop (count-if #'is-lens content)) + (append content (list (cons label focal-length))) + (mapcar + (lambda (c) (if (is-lens c) + (cons label focal-length) + c)) + content)))) + (setf (aref boxes (hash label))))))) + boxes) + +(defun focusing-power (boxes) + (loop for i from 1 + for lenses across boxes + sum + (* i (loop for j from 1 + for (l . fl) in lenses + sum (* j fl))))) + (fiveam:test solutions (fiveam:is (= 52 (hash "HASH"))) (fiveam:is (= 1320 (solve1 eg-in))) - (fiveam:is (= 506437 (solve1 (uiop:read-file-string "input"))))) - -(fiveam:run!) + (fiveam:is (= 506437 (solve1 (uiop:read-file-string "input")))) + (fiveam:is (= 145 (focusing-power (implement-instructions eg-in)))) + (fiveam:is (= 288521 (focusing-power (implement-instructions (uiop:read-file-string "input")))))) -- cgit v1.2.3