aboutsummaryrefslogtreecommitdiffstats
path: root/AoC2022/10/solver.lisp
blob: a30aa56cf3a3da19d067487c43414a06dcf0a270 (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
48
49
50
51
(ql:quickload '(:fiveam))

(defun probe (cycle register)
  (when (member cycle '(20 60 100 140 180 220) :test #'eq)
    (* cycle register)))

(defun draw-pixel (cycle register)
  (let ((pixel (mod (1- cycle) 40)))
    (when (= 0 pixel)
      (terpri))
    (princ (if (<= (1- register) pixel (1+ register))
               "#" ".")))
  (1+ cycle))

(defun solver (data-file)
  (let ((register 1) (cycle 1)
        (*standard-output* (make-string-output-stream)))
    (list
     (with-open-file (in data-file)
       (loop for inst = (read in nil nil)
             while inst
             when (progn (setf cycle (draw-pixel cycle register))
                         (let ((step1 (probe cycle register))
                               (step2
                                 (when (eq 'addx inst)
                                   (setf cycle (draw-pixel cycle register))
                                   (incf register (read in nil 0))
                                   (probe cycle register))))
                           (or step1 step2)))
               sum it))
     (get-output-stream-string *standard-output*))))

(fiveam:test results
             (fiveam:is (equal (solver "eg-in")
                               (list 13140 "
##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######.....")))
             (fiveam:is (equal (solver "input")
                               (list 12540  "
####.####..##..####.####.#....#..#.####.
#....#....#..#....#.#....#....#..#.#....
###..###..#......#..###..#....####.###..
#....#....#.....#...#....#....#..#.#....
#....#....#..#.#....#....#....#..#.#....
#....####..##..####.####.####.#..#.####."))))

(fiveam:run-all-tests)