Created
December 7, 2021 15:04
-
-
Save death/c70dd1ed7b57b61559b06e981b0bcae8 to your computer and use it in GitHub Desktop.
aoc2021-day7
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 2021 | | |
;;;; +----------------------------------------------------------------+ | |
(defpackage #:snippets/aoc2021/day7 | |
(:use #:cl) | |
(:import-from | |
#:alexandria) | |
(:export | |
#:day7)) | |
(in-package #:snippets/aoc2021/day7) | |
(defun sum-absolute-error (positions choice) | |
(loop for position in positions | |
sum (abs (- position choice)))) | |
(defun min-sum-absolute-error (positions) | |
(sum-absolute-error positions (round (alexandria:median positions)))) | |
(defun sum-triangular-error (positions choice) | |
(loop for position in positions | |
for n = (abs (- position choice)) | |
sum (/ (* n (1+ n)) 2))) | |
(defun min-sum-triangular-error (positions) | |
;; Can't be arsed to implement weighted median :( | |
(loop for choice from 0 to (reduce #'max positions) | |
minimize (sum-triangular-error positions choice))) | |
(defun day7 (input) | |
(list (min-sum-absolute-error input) | |
(min-sum-triangular-error input))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment