1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- (defparameter *depths-input* "./input.txt")
- (defun read-depths ()
- "Read input file, returning a list of its depth readings."
- (let ((input (open *depths-input* :if-does-not-exist nil))
- (input-depths '()))
- (when input
- (loop for line = (read-line input nil)
- while line do
- (setq input-depths (cons (parse-integer line) input-depths)))
- (close input))
- (reverse input-depths)))
- (defun traverse (depths)
- "Calculate number of descents into the deep."
- (defun iter-traverse (current-depth remaining-readings descents)
- (let ((next-depth (car remaining-readings)))
- (cond ((eq remaining-readings 'nil) descents)
- ((< current-depth next-depth)
- (iter-traverse next-depth
- (cdr remaining-readings)
- (1+ descents)))
- ('true
- (iter-traverse next-depth
- (cdr remaining-readings)
- descents)))))
-
- (iter-traverse (car depths) depths 0))
- ;; get results!!
- (traverse (read-depths)) ;; 1215 descents
- (defun traverse-wide-window (depths)
- "Calculate number of descents into the deep using a three-measurement window."
- (defun iter-traverse (previous-window remaining-readings descents)
- (if (< (length remaining-readings) 3)
- descents
- (let* ((a (car remaining-readings))
- (b (cadr remaining-readings))
- (c (caddr remaining-readings))
- ;; 199 A
- ;; 200 A B
- ;; 208 A B C Start by comparing the first and second three-measurement windows.
- ;; 210 B C D The measurements in the first window are marked A (199, 200, 208);
- ;; 200 E C D their sum is 199 + 200 + 208 = 607. The second window is marked
- ;; 207 E F D B (200, 208, 210); its sum is 618. The sum of measurements in the
- ;; 240 E F G second window is larger than the sum of the first, so this first
- ;; 269 F G H comparison increased.
- ;; 260 G H
- ;; 263 H
- (window (+ a b c))
- (remaining-depths (cdr remaining-readings)))
- (cond ((= previous-window 0) ;; the first measurement -- not enough info to calculate depth
- (iter-traverse window remaining-depths
- descents))
- ((> window previous-window)
- (iter-traverse window remaining-depths
- (1+ descents)))
- ('true
- (iter-traverse window remaining-depths
- descents))))))
-
- (iter-traverse 0 depths 0))
- ;; get results!!
- (traverse-wide-window (read-depths)) ;; 1150 descents
|