summaryrefslogblamecommitdiffstats
path: root/day09.lisp
blob: 46374719a95ad160ea9481207f07f812d95f46cd (plain) (tree)








































                                                                                    
(defstruct problem reports)

(defun parse-integers (string &key (start 0))
  (loop for i = start then (cadr o)
        as o = (multiple-value-list (parse-integer string :start i :junk-allowed t))
        as n = (car o)
        while n
        collect n))

(defun parse-reports (stream)
  (loop for line = (read-line stream nil)
        while line
        collect (parse-integers line)))

(defun parse-problem (filespec)
  (with-open-file (stream filespec)
    (make-problem :reports (parse-reports stream))))

(defun report-next-level (report)
  (loop for i in (cdr report)
        for j in report
        collect (- i j)))

(defun report-next-value (report)
  (if (every (lambda (v) (= v 0)) report)
      0
      (+ (car (last report)) (report-next-value (report-next-level report)))))

(defun solve1 (filespec)
  (let ((problem (parse-problem filespec)))
    (reduce #'+ (mapcar #'report-next-value (problem-reports problem)))))

(defun solve2 (filespec)
  (let ((problem (parse-problem filespec)))
    (reduce #'+ (mapcar #'report-next-value
                        (mapcar #'reverse (problem-reports problem))))))

(print (solve1 "data/09/example.txt"))  ;; 114
(print (solve1 "data/09/input.txt"))    ;; 1916822650
(print (solve2 "data/09/example.txt"))  ;; 2
(print (solve2 "data/09/input.txt"))    ;; 966