(defpackage "AOC/14" (:use "CL"))
(in-package "AOC/14")
(defun turn (state)
(destructuring-bind (scoreboard elf-1 elf-2)
state
(multiple-value-bind (tens ones)
(floor (+ (aref scoreboard elf-1) (aref scoreboard elf-2)) 10)
(when (plusp tens)
(vector-push-extend tens scoreboard))
(vector-push-extend ones scoreboard))
(list scoreboard
(mod (+ 1 elf-1 (aref scoreboard elf-1)) (length scoreboard))
(mod (+ 1 elf-2 (aref scoreboard elf-2)) (length scoreboard)))))
(defun next-ten (n)
(loop for state = (list (make-array 2 :adjustable t :fill-pointer t :initial-contents '(3 7)) 0 1) then (turn state)
until (>= (length (first state)) n)
finally (dotimes (x 10 (format t "~{~a~}" (coerce (subseq (first state) n (+ n 10)) 'list)))
(setf state (turn state)))))
(defun solution-1 ()
(next-ten 505961))
(defun turn (state)
(destructuring-bind (scoreboard elf-1 elf-2)
state
(multiple-value-bind (tens ones)
(floor (+ (aref scoreboard elf-1) (aref scoreboard elf-2)) 10)
(when (plusp tens)
(vector-push-extend tens scoreboard))
(vector-push-extend ones scoreboard))
(list scoreboard
(mod (+ 1 elf-1 (aref scoreboard elf-1)) (length scoreboard))
(mod (+ 1 elf-2 (aref scoreboard elf-2)) (length scoreboard)))))
(defun first-appearance (s)
(let ((state (list (make-array 24000000 :adjustable t :fill-pointer 2 :element-type '(integer 0 10)) 0 1)))
(setf (aref (first state) 0) 3
(aref (first state) 1) 7)
(loop with s = (map 'cons (lambda (x) (- (char-code x) (char-code #\0))) s)
do (setf state (turn state))
until (and (>= (length (first state)) (length s))
(search s (subseq (first state) (- (length (first state)) (length s)))))
finally (return (search s (first state))))))
(defun solution-2 ()
(first-appearance "505961"))