day-3.lisp (1027B)
1 (defpackage #:aoc/day-3 2 (:use #:cl #:aoc/utils) 3 (:export #:day-3)) 4 (in-package #:aoc/day-3) 5 6 (defun try-read-number (stream) 7 (loop while (digit-char-p (peek-char nil stream)) 8 collect (read-char stream) into bag 9 finally (return (if bag 10 (parse-integer (coerce bag 'string)) 11 nil)))) 12 13 (define-parser day-3-parser (stream) 14 ((mul-enabled t) 15 (num-1 0) 16 (num-2 0) 17 (task-1 0) 18 (task-2 0)) 19 (#\d #\o #\( #\) (setf mul-enabled t)) 20 (#\d #\o #\n #\' #\t #\( #\) (setf mul-enabled nil)) 21 (#\m #\u #\l #\( 22 (setf num-1 (try-read-number stream)) 23 #\, 24 (setf num-2 (try-read-number stream)) 25 #\) 26 (let ((result (* num-1 num-2))) 27 (incf task-1 result) 28 (when mul-enabled 29 (incf task-2 result))))) 30 31 (defun day-3 (input) 32 (multiple-value-bind (mul-enabled num-1 num-2 task-1 task-2) 33 (day-3-parser input) 34 (declare (ignore mul-enabled num-1 num-2)) 35 (values task-1 task-2)))