Skip to content

Instantly share code, notes, and snippets.

@death
Created December 5, 2018 15:02
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/e0e216ca41eee99da609f01c64d2725a to your computer and use it in GitHub Desktop.
Save death/e0e216ca41eee99da609f01c64d2725a to your computer and use it in GitHub Desktop.
;;;; +----------------------------------------------------------------+
;;;; | Advent of Code 2018 |
;;;; +----------------------------------------------------------------+
(defpackage #:snippets/aoc2018/day5
(:use #:cl)
(:export
#:day5))
(in-package #:snippets/aoc2018/day5)
(defun eval-reactions-1 (polymer)
(with-output-to-string (stream)
(let ((i 0))
(loop
(cond ((= i (length polymer))
(return))
((and (< i (1- (length polymer)))
(reacting-pair-p (char polymer i)
(char polymer (1+ i))))
(incf i))
(t
(write-char (char polymer i) stream)))
(incf i)))))
(defun reacting-pair-p (unit1 unit2)
(and (char-equal unit1 unit2)
(char/= unit1 unit2)))
(defun eval-reactions (polymer)
(let ((new (eval-reactions-1 polymer)))
(if (= (length new) (length polymer))
polymer
(eval-reactions new))))
(defun unit-types (polymer)
(remove-duplicates polymer :test #'char-equal))
(defun eval-reactions-minimal (polymer)
(loop with min-length = (length polymer)
with min-value = polymer
for troublemaker in (unit-types polymer)
for value = (eval-reactions (remove troublemaker polymer :test #'char-equal))
for length = (length value)
when (< length min-length)
do (setf min-length length min-value value)
finally (return min-value)))
(defun day5 (input)
(list (length (eval-reactions input))
(length (eval-reactions-minimal input))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment