Last active
December 17, 2021 06:16
-
-
Save death/a9cd8e3fd0a6582e09e34445ad6fe234 to your computer and use it in GitHub Desktop.
aoc2021 day17
This file contains hidden or 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/day17 | |
(:use #:cl) | |
(:export | |
#:day17)) | |
(in-package #:snippets/aoc2021/day17) | |
(defstruct probe | |
step | |
max-height | |
position | |
velocity | |
goodp) | |
(defun within-target-area-p (probe target-area) | |
(destructuring-bind (x1 x2 y1 y2) target-area | |
(and (<= x1 (realpart (probe-position probe)) x2) | |
(<= y1 (imagpart (probe-position probe)) y2)))) | |
(defun init-probe (probe velocity target-area) | |
(setf (probe-step probe) 0) | |
(setf (probe-max-height probe) 0) | |
(setf (probe-position probe) #C(0 0)) | |
(setf (probe-velocity probe) velocity) | |
(setf (probe-goodp probe) (within-target-area-p probe target-area)) | |
probe) | |
(defun step-probe (probe target-area) | |
(incf (probe-step probe)) | |
(incf (probe-position probe) (probe-velocity probe)) | |
(setf (probe-max-height probe) | |
(max (probe-max-height probe) | |
(imagpart (probe-position probe)))) | |
(incf (probe-velocity probe) | |
(complex (- (signum (realpart (probe-velocity probe)))) | |
-1)) | |
(setf (probe-goodp probe) | |
(or (probe-goodp probe) | |
(within-target-area-p probe target-area))) | |
probe) | |
(defun stop-sim-p (probe target-area) | |
(destructuring-bind (x1 x2 y1 y2) target-area | |
(or (< (imagpart (probe-position probe)) (min y1 y2)) | |
(> (realpart (probe-position probe)) (max x1 x2))))) | |
(defun sim-probe (probe target-area &key verbose) | |
(do () | |
((stop-sim-p probe target-area) probe) | |
(when verbose | |
(format t "~3D ~3D ~3D~%" | |
(probe-step probe) | |
(realpart (probe-position probe)) | |
(imagpart (probe-position probe)))) | |
(step-probe probe target-area))) | |
(defun day17 (target-area) | |
(let ((max-height 0) | |
(num-good 0) | |
(min (reduce #'min target-area)) | |
(max (reduce #'max target-area)) | |
(probe (make-probe))) | |
(do ((x min (1+ x))) | |
((> x max)) | |
(do ((y min (1+ y))) | |
((> y max)) | |
(init-probe probe (complex x y) target-area) | |
(sim-probe probe target-area) | |
(when (probe-goodp probe) | |
(setf max-height | |
(max max-height | |
(probe-max-height probe))) | |
(incf num-good)))) | |
(list max-height num-good))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment