aoc18/day1.lisp -rw-r--r-- 1.2 KiB View raw
                                                                                
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
(in-package :aoc18)

(defun read-lines (path)
  (let ((ret nil))
    (with-open-file (stream path)
      (do ((line (read-line stream nil)
                 (read-line stream nil)))
          ((null line))
        (setf ret (cons line ret))))
    (reverse ret)))

(defun file-string (path)
  (with-open-file (stream path)
    (let ((data (make-string (file-length stream))))
      (read-sequence data stream)
      data)))

(defun read-day1-input (path)
  (mapcar #'parse-integer (read-lines path)))

(defun solve-day1-part1 (input)
  (apply #'+ input))

(defun solve-day1-part2 (input)
  (let ((seen (make-hash-table))
	(current 0)
	(loops 0))
    (setf (gethash current seen) t)
    (loop do
	 (setf loops (+ 1 loops))
	 (loop for e in input do
	      (setf current (+ current e))
	      (if (gethash current seen)
		  (return-from solve-day1-part2 (values current loops)))
	      (setf (gethash current seen) t)))))

(test day1-part1
  (is (= 406 (solve-day1-part1 (read-day1-input "day1.input")))))

(test day1-part2
  (is (= 0 (solve-day1-part2 '(1 -1))))
  (is (= 10 (solve-day1-part2 '(+3 +3 +4 -2 -4))))
  (is (= 5 (solve-day1-part2 '(-6 +3 +8 +5 -6))))
  (is (= 14 (solve-day1-part2 '(+7 +7 -2 -7 -4))))
  (is (= 312 (solve-day1-part2 (read-day1-input "day1.input")))))