submarine.lisp 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. (defparameter *movements-input* "./input.txt")
  2. (ql:quickload :cl-strings)
  3. (use-package :cl-strings)
  4. (defun read-movements ()
  5. "Read input file, returning a list of its depth readings."
  6. (let ((input (open *movements-input* :if-does-not-exist nil))
  7. (input-movements '()))
  8. (when input
  9. (loop with direction and distance
  10. for line = (read-line input nil)
  11. while line do
  12. (setf direction (car (cl-strings:split line)))
  13. (setf distance (parse-integer (cadr (cl-strings:split line))))
  14. (setq input-movements (cons (cons direction distance) input-movements)))
  15. (close input))
  16. (reverse input-movements)))
  17. (defun calculate-depths (input)
  18. "Calculate trajectory thru the deep."
  19. (defun iter-movements (movements horizontal depth)
  20. (cond ((eq movements '())
  21. (cons horizontal depth))
  22. ('true
  23. (let* ((movement (car movements))
  24. (direction (car movement))
  25. (distance (cdr movement)))
  26. (cond ((string= direction "up")
  27. (iter-movements
  28. (cdr movements)
  29. horizontal
  30. (- depth distance)))
  31. ((string= direction "down")
  32. (iter-movements
  33. (cdr movements)
  34. horizontal
  35. (+ depth distance)))
  36. ((string= direction "forward")
  37. (iter-movements
  38. (cdr movements)
  39. (+ horizontal distance)
  40. depth)))))))
  41. (iter-movements input 0 0))
  42. ;; get measurements!!
  43. (calculate-depths (read-movements)) ;; (1868 . 1090)
  44. (let* ((calculations
  45. (calculate-depths (read-movements)))
  46. (horizontal (car calculations))
  47. (depth (cdr calculations)))
  48. (* horizontal depth)) ;; results: 2036120
  49. (defun calculate-depths-with-aim (input)
  50. "Calculate trajectory thru the deep, understanding aim."
  51. (defun iter-movements (movements horizontal depth aim)
  52. (if ((eq movements '())
  53. (cons horizontal depth))
  54. (let* ((movement (car movements))
  55. (direction (car movement))
  56. (units (cdr movement)))
  57. (cond ((string= direction "up")
  58. (iter-movements
  59. (cdr movements)
  60. horizontal
  61. depth
  62. (- aim units)))
  63. ((string= direction "down")
  64. (iter-movements
  65. (cdr movements)
  66. horizontal
  67. depth
  68. (+ aim units)))
  69. ((string= direction "forward")
  70. (iter-movements
  71. (cdr movements)
  72. (+ horizontal units)
  73. (+ depth (* units aim))
  74. aim))))))
  75. (iter-movements input 0 0 0))
  76. ;; get measurements!!
  77. (calculate-depths-with-aim (read-movements)) ;; (1868 . 1078987)
  78. (let* ((calculations
  79. (calculate-depths-with-aim (read-movements)))
  80. (horizontal (car calculations))
  81. (depth (cdr calculations)))
  82. (* horizontal depth)) ;; results: 2015547716