aoc/2021/06/06.lisp

65 lines
1.4 KiB
Common Lisp

(load (merge-pathnames "../common.lisp" *load-truename*))
(defconstant test-data
'(
"abc"
""
"a"
"b"
"c"
""
"ab"
"ac"
""
"a"
"a"
"a"
"a"
""
"b"
))
(defun array-to-list (array)
(map 'list #'identity array))
(defun character-counts (group)
(loop for answers in group
with counts = (make-array 26)
do (loop for answer across answers
do (incf (aref counts (- (char-code answer) (char-code #\a)))))
finally (return (array-to-list counts))))
(defun answered-yes (group)
(length (remove-if #'zerop (character-counts group))))
(defun all-answered-yes (group)
(let ((group-size (length group)))
(length (remove-if-not (lambda (e) (= e group-size)) (character-counts group)))))
(let ((input '("abcx" "abcy" "abcz")))
(assert (= 6 (answered-yes input)))
(assert (= 3 (all-answered-yes input))))
(defun groups (input)
(loop for x = 0 then (1+ j)
as j = (position "" input :start x :test #'string=)
collect (subseq input x j)
while j))
(defun solve (input f)
(apply '+ (mapcar f (groups input))))
(defun part1 (input)
(solve input #'answered-yes))
(defun part2 (input)
(solve input #'all-answered-yes))
(assert (= 11 (part1 test-data)))
(assert (= 6 (part2 test-data)))
(let ((input (read-data)))
(format t "Part 1: ~A~%" (part1 input))
(format t "Part 2: ~A~%" (part2 input)))