Last active
December 3, 2021 06:58
-
-
Save death/ca6e8754afdcce8c358b346d902519d1 to your computer and use it in GitHub Desktop.
aoc2021-day3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ;;;; +----------------------------------------------------------------+ | |
| ;;;; | Advent of Code 2021 | | |
| ;;;; +----------------------------------------------------------------+ | |
| (defpackage #:snippets/aoc2021/day3 | |
| (:use #:cl) | |
| (:export | |
| #:day3)) | |
| (in-package #:snippets/aoc2021/day3) | |
| (defun decode-1 (string) | |
| (map 'bit-vector #'digit-char-p string)) | |
| (defun decode (input) | |
| (mapcar #'decode-1 input)) | |
| (defun elt-at (position) | |
| (lambda (sequence) | |
| (elt sequence position))) | |
| (defun count-bit (bit-vectors position bit) | |
| (count bit bit-vectors :key (elt-at position))) | |
| (defun most (c0 c1) | |
| (if (> c0 c1) 0 1)) | |
| (defun least (c0 c1) | |
| (if (> c0 c1) 1 0)) | |
| (defun decide-bit (bit-vectors position which) | |
| (let* ((c0 (count-bit bit-vectors position 0)) | |
| (c1 (- (length bit-vectors) c0))) | |
| (funcall which c0 c1))) | |
| (defun get-bits (bit-vectors which) | |
| (coerce | |
| (loop for i below (length (first bit-vectors)) | |
| collect (decide-bit bit-vectors i which)) | |
| 'bit-vector)) | |
| (defun keep (bit-vectors position bit) | |
| (remove bit bit-vectors :key (elt-at position) :test #'/=)) | |
| (defun select (bit-vectors which) | |
| (do ((i 0 (1+ i)) | |
| (remaining bit-vectors | |
| (keep remaining i (decide-bit remaining i which)))) | |
| ((null (rest remaining)) | |
| (first remaining)))) | |
| (defun bit-vector-integer (bit-vector) | |
| (let ((bits 0) | |
| (n (length bit-vector))) | |
| (dotimes (i n) | |
| (setf (ldb (byte 1 (- n i 1)) bits) | |
| (aref bit-vector i))) | |
| bits)) | |
| (defun integer-product (bit-vector-1 bit-vector-2) | |
| (* (bit-vector-integer bit-vector-1) | |
| (bit-vector-integer bit-vector-2))) | |
| (defun power-consumption (bit-vectors) | |
| (integer-product (get-bits bit-vectors #'most) | |
| (get-bits bit-vectors #'least))) | |
| (defun life-support-rating (bit-vectors) | |
| (integer-product (select bit-vectors #'most) | |
| (select bit-vectors #'least))) | |
| (defun day3 (input) | |
| (let ((bit-vectors (decode input))) | |
| (list (power-consumption bit-vectors) | |
| (life-support-rating bit-vectors)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment