commit e13fadabbc3961d0288b7b894ed49eabe8c7c194 parent e512d75fa75e3917eff343c99be4cec0b601f20f Author: Lukas Henkel <lh@entf.net> Date: Mon, 4 Dec 2023 06:40:04 +0100 Day 4 task 2 Diffstat:
M | src/day-4.lisp | | | 31 | +++++++++++++++++++++++++++++-- |
M | t/day-4.lisp | | | 8 | +++++--- |
2 files changed, 34 insertions(+), 5 deletions(-)
diff --git a/src/day-4.lisp b/src/day-4.lisp @@ -34,9 +34,36 @@ (* score 2))) finally (return score))) +(declaim (ftype (function (list list) fixnum) card-matching-numbers)) +(defun card-matching-numbers (winning-numbers my-numbers) + (loop for number fixnum in my-numbers + when (member number winning-numbers) + sum 1 fixnum)) + +(declaim (ftype (function (list) (values fixnum list)) process-copies)) +(defun process-copies (copies) + (loop with total-copies fixnum = 0 + with new-copies = nil + for copy fixnum in copies + do (decf copy) + when (>= copy 0) + do (incf total-copies) + when (> copy 0) + do (push copy new-copies) + finally (return (values total-copies new-copies)))) + (defun day-4 (input) - (loop for line = (read-line input nil) + (loop with copies = nil + with task-2 fixnum = 0 + for line = (read-line input nil) while line for (winning-numbers my-numbers) = (read-card-numbers line) + for matching-numbers = (card-matching-numbers winning-numbers my-numbers) + do (multiple-value-bind (this-card-copies new-copies) + (process-copies copies) + (incf task-2 (1+ this-card-copies)) + (setf copies new-copies) + (loop for copy from 0 to this-card-copies + do (push matching-numbers copies))) sum (task-1 winning-numbers my-numbers) into task-1 fixnum - finally (return (values task-1)))) + finally (return (values task-1 task-2)))) diff --git a/t/day-4.lisp b/t/day-4.lisp @@ -4,10 +4,12 @@ (define-test test-day-4 () - (assert= 13 - (aoc:run-day 4 "Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53 + (multiple-value-bind (task-1 task-2) + (aoc:run-day 4 "Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53 Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19 Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1 Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83 Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36 -Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11"))) +Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11") + (assert= 13 task-1) + (assert= 30 task-2)))