Skip to content

Instantly share code, notes, and snippets.

@death
Created December 3, 2018 21:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save death/fd93cf68c475a303c07a2ae5890439e9 to your computer and use it in GitHub Desktop.
Save death/fd93cf68c475a303c07a2ae5890439e9 to your computer and use it in GitHub Desktop.
Advent of Code 2018 - Day 3
;;;; +----------------------------------------------------------------+
;;;; | Advent of Code 2018 |
;;;; +----------------------------------------------------------------+
(defpackage #:snippets/aoc2018/day3
(:use #:cl)
(:import-from #:split-sequence
#:split-sequence
#:split-sequence-if)
(:import-from #:parse-number
#:parse-number)
(:import-from #:alexandria
#:maxf)
(:export
#:day3))
(in-package #:snippets/aoc2018/day3)
(defclass claim ()
((id :initarg :id :reader id)
(top :initarg :top :reader top)
(left :initarg :left :reader left)
(width :initarg :width :reader width)
(height :initarg :height :reader height)))
(defmethod bottom ((claim claim))
(+ (top claim) (height claim)))
(defmethod right ((claim claim))
(+ (left claim) (width claim)))
(defun parse-claim (string)
(destructuring-bind (id left top width height)
(mapcar #'parse-number
(split-sequence-if (complement #'digit-char-p)
string
:remove-empty-subseqs t))
(make-instance 'claim
:id id
:top top
:left left
:width width
:height height)))
(defun parse-claims (input)
(etypecase input
(list
(mapcar #'parse-claim input))
(string
(parse-claims
(split-sequence #\Newline
input
:remove-empty-subseqs t)))))
(defun bounds (claims)
(let ((width 0)
(height 0))
(dolist (claim claims)
(maxf width (right claim))
(maxf height (bottom claim)))
(list height width)))
(defun day3 (input)
(let* ((claims (parse-claims input))
(cells (make-array (bounds claims) :initial-element '()))
(total 0)
(overlapping (make-hash-table)))
(dolist (claim claims)
(loop for r from (top claim) below (bottom claim)
do (loop for c from (left claim) below (right claim)
do (push claim (aref cells r c))
do (let ((count (length (aref cells r c))))
(when (= count 2)
(incf total))
(when (> count 1)
(dolist (claim-in-cell (aref cells r c))
(setf (gethash claim-in-cell overlapping) t)))))))
(list total
(id
(loop for claim in claims
unless (gethash claim overlapping)
return claim)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment