solved day 3

This commit is contained in:
Peter Tillemans 2024-12-03 08:13:45 +01:00
parent 70f2a5d8da
commit 9855cf3ac9
2 changed files with 94 additions and 0 deletions

76
src/2024/day03.lisp Normal file
View file

@ -0,0 +1,76 @@
(defpackage :aoc/2024/03
(:use :cl :aoc :alexandria)
(:export
#:sample-data
#:sample-data2
#:part1
#:part2
))
(in-package :aoc/2024/03)
(defun parse-line (s)
(let ((multiplications '()))
(cl-ppcre:do-register-groups (a b c d)
("mul\\((\\d+),(\\d+)\\)|(do)\\(\\)|(don't)\\(\\)" s)
(push
(cond
(a (list (parse-integer a) (parse-integer b)))
(c :do)
(d :dont))
multiplications))
(reverse multiplications)))
(defvar input-data '())
(setf input-data (map 'list #'parse-line (test-input 2024 3)))
(defvar sample-text "")
(setf sample-text (aoc:split-lines "xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))"))
(defvar sample-data '())
(setf sample-data (map 'list #'parse-line sample-text))
(defun add-multiply (data)
(first
(reduce
(lambda (acc x)
(let ((sum (first acc))
(enable (second acc)))
(if (listp x)
(list (+ sum (if enable (* (first x) (second x)) 0)) enable)
(list sum enable))))
data
:initial-value (list 0 t)
)))
(defun part1 (data)
(format nil "~A" (add-multiply (reduce #'append data))))
(defvar sample-text2 "")
(setf sample-text2 (aoc:split-lines "xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))"))
(defvar sample-data2 '())
(setf sample-data2 (map 'list #'parse-line sample-text2))
(defun interprete (data)
(first
(reduce
(lambda (acc x)
(let ((sum (first acc))
(enable (second acc)))
(cond
((eq x :do) (list sum t))
((eq x :dont) (list sum nil))
((listp x) (list (+ sum (if enable (* (first x) (second x)) 0)) enable))
(t (format nil "****ERROR**** Unexpected input: ~A~%" x)))))
data
:initial-value (list 0 t)
)))
(defun part2 (data)
(format nil "~A" (interprete (reduce #'append data))))
(defun solve-day ()
(format t "part1: ~A~%" (part1 input-data))
(format t "part2: ~A~%" (part2 input-data)))

View file

@ -0,0 +1,18 @@
(defpackage :aoc/2024/03/tests
(:use :cl :aoc :aoc/tests :aoc/2024/tests :parachute :aoc/2024/03))
(in-package :aoc/2024/03/tests)
(define-test suite-2024-03
;:parent suite-2024
)
(define-test+run test-part1
:parent suite-2024-03
(true (equalp "161" (part1 sample-data))))
(define-test+run test-part2
:parent suite-2024-03
(true (equalp "48" (part2 sample-data2))))