Skip to content

Instantly share code, notes, and snippets.

@death
Last active December 11, 2021 06:00
Show Gist options
  • Select an option

  • Save death/6c180649c13eaee8476405d981f458aa to your computer and use it in GitHub Desktop.

Select an option

Save death/6c180649c13eaee8476405d981f458aa to your computer and use it in GitHub Desktop.
aoc2021 day11
;;;; +----------------------------------------------------------------+
;;;; | Advent of Code 2021 |
;;;; +----------------------------------------------------------------+
(defpackage #:snippets/aoc2021/day11
(:use #:cl)
(:export
#:day11))
(in-package #:snippets/aoc2021/day11)
(defun make-grid (lines)
(let ((grid (make-array (list (length lines) (length (first lines)))
:initial-element 0)))
(loop for i upfrom 0
for line in lines
do (loop for j upfrom 0
for char across line
do (setf (aref grid i j) (digit-char-p char))))
grid))
(defun sim-step (grid)
(let ((agenda '())
(num-flash 0)
(reset '()))
(destructuring-bind (rows cols) (array-dimensions grid)
(dotimes (i rows)
(dotimes (j cols)
(push (list i j) agenda)))
(loop until (null agenda)
do (let ((indices (pop agenda)))
(destructuring-bind (i j) indices
(incf (aref grid i j))
(when (= (aref grid i j) 10)
(push indices reset)
(incf num-flash)
(loop for di in '(-1 0 +1)
for ni = (+ i di)
do (loop for dj in '(-1 0 +1)
for nj = (+ j dj)
when (and (not (= di dj 0))
(array-in-bounds-p grid ni nj))
do (push (list ni nj) agenda)))))))
(loop for (i j) in reset
do (setf (aref grid i j) 0))
num-flash)))
(defun day11 (input)
(do ((grid (make-grid input))
(total-after-100-steps 0)
(all-flash-step nil)
(step 1 (1+ step)))
((and (> step 100) (not (null all-flash-step)))
(list total-after-100-steps all-flash-step))
(let ((num-flash (sim-step grid)))
(when (<= step 100)
(incf total-after-100-steps num-flash))
(when (and (null all-flash-step)
(= num-flash (array-total-size grid)))
(setf all-flash-step step)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment