Skip to content

Instantly share code, notes, and snippets.

@commander-trashdin
Created December 4, 2021 21:57
Show Gist options
  • Select an option

  • Save commander-trashdin/a90645d6eda8dd134cd7b0f0aaf79f9c to your computer and use it in GitHub Desktop.

Select an option

Save commander-trashdin/a90645d6eda8dd134cd7b0f0aaf79f9c to your computer and use it in GitHub Desktop.
AoC 2021, day 4, not too bad
(defmacro do-table (indexes &body body)
(if (null indexes)
`(progn ,@body)
`(loop :for ,(caar indexes) :from 0 :below ,(cadar indexes)
:do (do-table ,(cdr indexes) ,@body))))
(defun read-nums (stream)
(map 'vector #'parse-integer
(uiop:split-string
(read-line stream)
:separator '(#\,))))
(defun read-5x5-matrix-into (matrix stream)
(do-table ((i 5) (j 5))
(setf (aref matrix i j) (read stream)))
matrix)
(defun order (array)
(let ((order (make-array (length array))))
(loop :for i :from 0 :below (length array)
:do (setf (aref order (aref array i)) i))
order))
(defun win-time (matrix order)
(let ((matrix-time (length order)))
(loop :for i :from 0 :below 5
:do (let ((line-time 0))
(loop :for j :from 0 :below 5
:do (setf line-time
(max line-time
(aref order (aref matrix i j)))))
(setf matrix-time
(min matrix-time line-time))))
(loop :for i :from 0 :below 5
:do (let ((column-time 0))
(loop :for j :from 0 :below 5
:do (setf column-time
(max column-time
(aref order (aref matrix j i)))))
(setf matrix-time
(min matrix-time column-time))))
matrix-time))
(defun day4.1 (pathname)
(with-open-file (stream pathname :direction :input)
(let* ((nums (read-nums stream))
(order (order nums))
(matrix (make-array '(5 5) :element-type 'fixnum))
(min (length order))
(winner (make-array '(5 5) :element-type 'fixnum)))
(loop :while (peek-char t stream nil nil)
:do (read-5x5-matrix-into matrix stream)
(let ((win-time (win-time matrix order)))
(when (> min win-time)
(do-table ((i 5) (j 5))
(setf (aref winner i j)
(aref matrix i j)))
(setf min win-time))))
(let ((unmarked-sum 0))
(do-table ((i 5) (j 5))
(when (> (aref order (aref winner i j))
min)
(incf unmarked-sum (aref winner i j))))
(* unmarked-sum (aref nums min))))))
(defun day4.2 (pathname)
(with-open-file (stream pathname :direction :input)
(let* ((nums (read-nums stream))
(order (order nums))
(matrix (make-array '(5 5) :element-type 'fixnum))
(max 0)
(loser (make-array '(5 5) :element-type 'fixnum)))
(loop :while (peek-char t stream nil nil)
:do (read-5x5-matrix-into matrix stream)
(let ((win-time (win-time matrix order)))
(when (< max win-time)
(do-table ((i 5) (j 5))
(setf (aref loser i j)
(aref matrix i j)))
(setf max win-time))))
(let ((unmarked-sum 0))
(do-table ((i 5) (j 5))
(when (> (aref order (aref loser i j))
max)
(incf unmarked-sum (aref loser i j))))
(* unmarked-sum (aref nums max))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment