;;; Day 1 (defun read-1 (file) (with-open-file (stream file) (loop for line = (read-line stream nil) while line collect (parse-integer line)))) (defun solve-1-1 (file) (let ((readings (read-1 file)) (inc-acc 0)) (labels ((rec (list old) (if list (progn (if (< old (first list)) (incf inc-acc)) (rec (cdr list) (first list)))))) (rec (cdr readings) (first readings)) inc-acc))) (defun solve-1-2 (file) (let ((readings (read-1 file)) (inc-acc 0)) (labels ((rec (list old-sum) (if (cddr list) (let ((sum (reduce #'+ (subseq list 0 3)))) (if (< old-sum sum) (incf inc-acc)) (rec (cdr list) sum))))) (rec (cdr readings) (reduce #'+ (subseq readings 0 3))) inc-acc))) ;;; Day 2 (defun setup-solution-2 (stage) (let ((position (vector 0 0)) (aim 0)) (defun forward (n) (incf (elt position 0) n) (if (= stage 2) (incf (elt position 1) (* n aim)))) (defun up (n) (if (= stage 1) (decf (elt position 1) n) (decf aim n))) (defun down (n) (if (= stage 1) (incf (elt position 1) n) (incf aim n))) (defun zero () (setf position (vector 0 0) aim 0)) (defun result () position))) (defun read-2-1 (file) (with-open-file (stream file) (loop for line = (read-line stream nil) while line collect (multiple-value-bind (symbol length) (read-from-string line) (list symbol (parse-integer (subseq line length))))))) (defun solve-2-1 (data) (setup-solution-2 1) (eval (cons 'progn data)) (reduce #'* (result))) (defun solve-2-2 (data) (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))))