aoc-2022/common-lisp/day-10/solution.lisp
2022-12-28 03:47:10 -05:00

61 lines
2.3 KiB
Common Lisp
Executable file

#!/usr/bin/env -S sbcl --script
;; Copyright (C) 2022
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <https://www.gnu.org/licenses/>.
(require 'asdf)
(require 'uiop)
(require 'str)
(require 'iterate)
(defpackage :advent-of-code-day-10
(:use :cl :iterate)
(:import-from :uiop :read-file-lines))
(in-package :advent-of-code-day-10)
(defun signal-strength-at-cycle (instructions cycle)
(iter (for instruction in instructions)
(for noop? = (not (consp instruction)))
(for counter initially 1 then (+ counter (if noop? 1 2)))
(for register initially 1 then (if noop? register (+ register (cdr instruction))))
(for previous-counter previous counter)
(for previous-register previous register)
(when (> counter cycle)
(return (* cycle previous-register)))))
(defun parse-input (lines)
(iter (for line in lines)
(collect (if (string= line "noop")
:noop
(cons :addx (parse-integer (cadr (str:split " " line))))))))
(let ((input (parse-input (read-file-lines "example.txt"))))
(assert (= 420 (signal-strength-at-cycle input 20)))
(assert (= 1140 (signal-strength-at-cycle input 60)))
(assert (= 1800 (signal-strength-at-cycle input 100)))
(assert (= 2940 (signal-strength-at-cycle input 140)))
(assert (= 2880 (signal-strength-at-cycle input 180)))
(assert (= 3960 (signal-strength-at-cycle input 220)))
(assert (= 13140 (iter (for cycle from 20 to 220 by 40)
(sum (signal-strength-at-cycle input cycle))))))
(let ((input (parse-input (read-file-lines "input.txt"))))
(assert (= 14320 (iter (for cycle from 20 to 240 by 40)
(sum (signal-strength-at-cycle input cycle))))))
;; Local Variables:
;; mode: lisp
;; End: