Skip to content

Instantly share code, notes, and snippets.

@rhinoman
Last active December 7, 2017 13:11
Show Gist options
  • Save rhinoman/04e8ca27dabd585581ada54c8ffd2865 to your computer and use it in GitHub Desktop.
Save rhinoman/04e8ca27dabd585581ada54c8ffd2865 to your computer and use it in GitHub Desktop.
Advent of Code 2017 day 6 solution
; Returns the index of the largest value
(defun maxv (xs)
(let* ((idx 1)
(mxidx 0)
(mxval (aref xs 0)))
(while (< idx (length xs))
(if (> (aref xs idx) mxval)
(progn
(setq mxval (aref xs idx))
(setq mxidx idx)))
(setq idx (+ idx 1)))
mxidx))
(defun distribute (xs)
(let* ((mx-idx (maxv xs))
(mx-val (aref xs mx-idx))
(idx (+ mx-idx 1)))
(aset xs mx-idx 0) ;set largest bank to 0
(while (> mx-val 0)
(if (>= idx (length xs))
(setq idx 0)) ;check for rollover
(aset xs idx (+ (aref xs idx) 1))
(setq mx-val (- mx-val 1))
(setq idx (+ idx 1)))
)
)
(defun solve (raw)
(let* ((xs (copy-sequence raw))
(st (make-hash-table :test 'equal))
(cycle nil)
(num-steps 0)
(num-iters 0))
(while (not cycle)
(puthash (md5 (mapconcat 'number-to-string xs ",")) num-steps st)
(distribute xs)
(setq num-steps (+ num-steps 1))
(if (gethash (md5 (mapconcat 'number-to-string xs ",")) st)
(setq cycle t))
)
(let ((iter-count (gethash (md5 (mapconcat 'number-to-string xs ",")) st)))
`((steps . ,num-steps)
(iters-to-cycle . ,(- num-steps iter-count)))
)
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment