From c5a03887370dda0d142dee7b6812bfe7b47ccedc Mon Sep 17 00:00:00 2001 From: 4903000 <4903000@chiru.no> Date: Sat, 4 Dec 2021 01:06:49 +0000 Subject: [PATCH] Day 3 --- aoc21.lisp | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/aoc21.lisp b/aoc21.lisp index 0e023ee..07c2ab0 100644 --- a/aoc21.lisp +++ b/aoc21.lisp @@ -67,3 +67,49 @@ (setup-solution-2 2) (eval (cons 'progn data)) (reduce #'* (result))) + +;;; Day 3 + +(defun vector+ (&rest vectors) + (labels ((internal (old new) + (map 'vector (lambda (n m) (+ n m)) old new))) + (reduce #'internal vectors))) + +(defun read-3 (file) + (with-open-file (stream file) + (loop for line = (read-line stream nil) + while line + collect (map 'vector (lambda (c) (- (char-code c) 48)) + line)))) + +(defun solve-3-1 (data) + (let* ((max (/ (length data) 2)) + (sums (reduce #'vector+ data)) + (gamma (map 'string (lambda (i) (digit-char (if (< 0 (- i max)) 1 0))) sums)) + (epsilon (map 'string (lambda (c) (if (char= c #\1) #\0 #\1)) gamma))) + (* (parse-integer gamma :radix 2) + (parse-integer epsilon :radix 2)))) + +(defun rec (data acc head bias) + (if data + (rec (cdr data) + (if (= (elt (first data) head) bias) + (list (cons (first data) (first acc)) (second acc)) + (list (first acc) (cons (first data) (second acc)))) + head bias) + (if (funcall ((lambda () (if (= bias 1) #'< #'>))) + (length (first acc)) (length (second acc))) + (second acc) + (first acc)))) + +(defun recrec (data head bias) + (let ((new-data (rec data (list nil nil) head bias))) + (if (= (length new-data) 1) + (first new-data) + (recrec new-data (+ 1 head) bias)))) + +(defun solve-3-2 (data) + (let ((oxygen (map 'string (lambda (n) (digit-char n)) (recrec data 0 1))) + (co2 (map 'string (lambda (n) (digit-char n)) (recrec data 0 0)))) + (* (parse-integer oxygen :radix 2) + (parse-integer co2 :radix 2))))