Advertisement
Guest User

Advent of Code: Day 8

a guest
Dec 9th, 2020
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lisp 1.73 KB | None | 0 0
  1. (defun parse-instruction (input)
  2.   (with-input-from-string (s input)
  3.     (list (read s)
  4.           (read s))))
  5.  
  6. (defun parse-program (input)
  7.   (apply #'vector (utils:map-line #'parse-instruction input)))
  8.  
  9. (defparameter *input* (parse-program (utils:read-file "8.dat")))
  10.  
  11. (defun run (program &optional fix-p)
  12.     "RUNs a PROCESS until it stops. Returns the accumulator and the call history
  13. or NIL if the program doesn't stop. When FIX-P is true, RUN tries to fix a
  14. potential infinite loop by changing one NOP to JMP or one JMP to NOP. Stops when
  15. the first branched halts. "
  16.   (catch 'found
  17.     (labels ((aux (fixed-p &optional (acc 0) (pc 0) calls)
  18.                (let (instruction op arg)
  19.                  (loop
  20.                    (when (>= pc (length program))
  21.                      (throw 'found (values acc (reverse calls) :halt)))
  22.                    (when (and (member pc calls))
  23.                      (if fix-p
  24.                          (return)
  25.                          (throw 'found (values acc (reverse calls) :loop))))
  26.                    (setf instruction (aref program pc))
  27.                    (setf op (car instruction))
  28.                    (setf arg (cadr instruction))
  29.                    (push pc calls)
  30.                    (case op
  31.                      (nop
  32.                       (unless fixed-p
  33.                         (aux t acc (+ pc arg) calls))
  34.                       (incf pc))
  35.                      (acc (incf acc arg) (incf pc))
  36.                      (jmp
  37.                       (unless fixed-p
  38.                         (aux t acc (1+ pc) calls))
  39.                       (incf pc arg)))))))
  40.       (aux (not fix-p)))))
  41.  
  42. (defun part-1 ()
  43.   (run (parse-program *input*)))
  44.  
  45. (defun part-2 ()
  46.   (run (parse-program *input*) t))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement