submarine.lisp 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. (defparameter *depths-input* "./input.txt")
  2. (defun read-depths ()
  3. "Read input file, returning a list of its depth readings."
  4. (let ((input (open *depths-input* :if-does-not-exist nil))
  5. (input-depths '()))
  6. (when input
  7. (loop for line = (read-line input nil)
  8. while line do
  9. (setq input-depths (cons (parse-integer line) input-depths)))
  10. (close input))
  11. (reverse input-depths)))
  12. (defun traverse (depths)
  13. "Calculate number of descents into the deep."
  14. (defun iter-traverse (current-depth remaining-readings descents)
  15. (let ((next-depth (car remaining-readings)))
  16. (cond ((eq remaining-readings 'nil) descents)
  17. ((< current-depth next-depth)
  18. (iter-traverse next-depth
  19. (cdr remaining-readings)
  20. (1+ descents)))
  21. ('true
  22. (iter-traverse next-depth
  23. (cdr remaining-readings)
  24. descents)))))
  25. (iter-traverse (car depths) depths 0))
  26. ;; get results!!
  27. (traverse (read-depths)) ;; 1215 descents
  28. (defun traverse-wide-window (depths)
  29. "Calculate number of descents into the deep using a three-measurement window."
  30. (defun iter-traverse (previous-window remaining-readings descents)
  31. (if (< (length remaining-readings) 3)
  32. descents
  33. (let* ((a (car remaining-readings))
  34. (b (cadr remaining-readings))
  35. (c (caddr remaining-readings))
  36. ;; 199 A
  37. ;; 200 A B
  38. ;; 208 A B C Start by comparing the first and second three-measurement windows.
  39. ;; 210 B C D The measurements in the first window are marked A (199, 200, 208);
  40. ;; 200 E C D their sum is 199 + 200 + 208 = 607. The second window is marked
  41. ;; 207 E F D B (200, 208, 210); its sum is 618. The sum of measurements in the
  42. ;; 240 E F G second window is larger than the sum of the first, so this first
  43. ;; 269 F G H comparison increased.
  44. ;; 260 G H
  45. ;; 263 H
  46. (window (+ a b c))
  47. (remaining-depths (cdr remaining-readings)))
  48. (cond ((= previous-window 0) ;; the first measurement -- not enough info to calculate depth
  49. (iter-traverse window remaining-depths
  50. descents))
  51. ((> window previous-window)
  52. (iter-traverse window remaining-depths
  53. (1+ descents)))
  54. ('true
  55. (iter-traverse window remaining-depths
  56. descents))))))
  57. (iter-traverse 0 depths 0))
  58. ;; get results!!
  59. (traverse-wide-window (read-depths)) ;; 1150 descents