aboutsummaryrefslogtreecommitdiffstats
path: root/AoC2022/10/solver.el
blob: d87ca0b70ec1882f74aad4081c50e1df805016de (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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
;;; solver.el --- Day 10 -*- lexical-binding: t; -*-
;;
;; Copyright (C) 2022 Óscar Nájera
;;
;; Author: Óscar Nájera <hi@oscarnajera.com>
;; Maintainer: Óscar Nájera <hi@oscarnajera.com>
;; Created: December 10, 2022
;; Modified: December 10, 2022
;;
;; This file is not part of GNU Emacs.
;;
;;; Commentary:
;;
;;  Day 10
;;
;;; Code:

(require 'subr-x)
(require 'cl-lib)
(require 'ert)

(defsubst solver-probe (cycle register)
  (when (memq cycle '(20 60 100 140 180 220))
    (* cycle register)))

(defsubst solver-draw-pixel (pixel register)
  (when (= 0 pixel)
    (insert "\n"))
  (insert
   (if (<= (1- register) pixel (1+ register))
       "#" ".")))

(defun solver-instructions (filename)
  (with-temp-buffer
    (insert-file-contents filename)
    (split-string (buffer-string) "\n")))

(defun solver (data-file)
  (let ((register 1) (cycle 1) measures)
    (with-temp-buffer
      (dolist (instruction (solver-instructions data-file))
        (solver-draw-pixel (mod (1- cycle) 40) register)
        (cl-incf cycle)
        (let ((step1 (solver-probe cycle register)) ;; the noop default
              (step2                                ;; addx takes 2 cycles
               (when (string-prefix-p "addx" instruction)
                 (solver-draw-pixel (mod (1- cycle) 40) register)
                 (cl-incf cycle)
                 (cl-incf register (string-to-number (cadr (split-string instruction))))
                 (solver-probe cycle register))))
          (when-let ((probe (or step1 step2)))
            (push probe measures))))
      (list
       (apply #'+ measures)
       (buffer-string)))))

(ert-deftest test-solver ()
  (should
   (equal (solver "eg-in")
          (list 13140 "
##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######.....
.")))
  (should
   (equal (solver "input")
          (list 12540 "
####.####..##..####.####.#....#..#.####.
#....#....#..#....#.#....#....#..#.#....
###..###..#......#..###..#....####.###..
#....#....#.....#...#....#....#..#.#....
#....#....#..#.#....#....#....#..#.#....
#....####..##..####.####.####.#..#.####.
."))))

(provide 'solver)
;;; solver.el ends here