aboutsummaryrefslogtreecommitdiffstats
path: root/AoC2022/01/solver.lisp
blob: dd09c078c4fce61174d857bd9fbd2c8546933340 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
; run sbcl --load ~/.sbclrc --script solver.lisp

(ql:quickload '(:uiop :fiveam))

(defun elves-rations (input)
    (reduce
     (lambda (acc value)
       (if (equal value "")
           (cons 0 acc)
           (progn
             (incf (car acc) (parse-integer value))
             acc)))
     input
     :initial-value (list 0)))

(defun elves-rations-nc (filename)
  (with-open-file (in filename)
    (let ((acc (list 0)))
      (loop for line = (read-line in nil) while line
            for num = (parse-integer line :junk-allowed t)
            if (numberp num) do
              (incf (car acc) num)
            else do
              (push 0 acc))
      acc)))

(defun elves-rations-max (filename)
  (with-open-file (in filename)
    (let ((max 0)
          (elf 0))
      (loop for line = (read-line in nil) while line
            for num = (parse-integer line :junk-allowed t)
            if (numberp num) do
              (incf elf num)
            else do
              (setf max (max elf max))
              (setf elf 0))
      (max elf max))))

(fiveam:test results
  (let ((rations (elves-rations (uiop:read-file-lines "input"))))
    ;; calculate the maximum from each elves rations
    (fiveam:is (= 75622 (reduce #'max rations)))
    (fiveam:is (= 75622 (reduce #'max (elves-rations-nc "input"))))
    (fiveam:is (= 75622 (elves-rations-max "input")))
    ;; calculate the maximum from each elves rations
    (fiveam:is (= 213159 (reduce #'+ (subseq (sort rations #'>) 0 3))))))