Created
December 5, 2018 15:02
-
-
Save death/e0e216ca41eee99da609f01c64d2725a to your computer and use it in GitHub Desktop.
This file contains 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 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