Skip to content

Instantly share code, notes, and snippets.

@pavloo
Created December 13, 2017 22:11
Show Gist options
  • Save pavloo/45b11d428d17083530e8409142992457 to your computer and use it in GitHub Desktop.
Save pavloo/45b11d428d17083530e8409142992457 to your computer and use it in GitHub Desktop.
(defun find-idx-of-max (list)
(let ((max_i 0) (val) (max))
(dotimes (i (length list) max_i)
(setq val (nth i list))
(setq max (nth max_i list))
(when (> val max) (setq max_i i))
)
)
)
(defun cycle-list (list start_i v)
(let ((i start_i) (val v))
(setf (nth i list) 0)
(setq i (1+ i))
(when (>= i (length list)) (setq i 0))
(while (> val 0)
(setf (nth i list) (1+ (nth i list)))
(setq val (1- val))
(setq i (1+ i))
(when (>= i (length list)) (setq i 0))
)
list
)
)
(defun reallocate-step (list)
(let ((n (length list)) i val rem)
(setq i (find-idx-of-max list))
(cycle-list list i (nth i list))
)
list
)
(defun get-pos (element list)
(let (idxs val)
(catch 'break
(dotimes (i (length list))
(setq val (nth i list))
(when (equal element val) (throw 'break i))
)
)
)
)
(get-pos 2 '(1 1 2)) ;; 2
(defun reallocate (list)
(let ((s 1) (results))
(reallocate-step list)
(while (and (not (member list results)) (< s 10000))
(push (copy-sequence list) results)
(reallocate-step list)
(setq s (1+ s))
)
(print results)
(print (format "Part #1: %d" s))
(print (format "Part #2: %d" (- (length results) (get-pos list (reverse results)))))
)
)
(reallocate '(0 2 7 0)) ;; 5
(reallocate-step '(0 2 7 0)) ;; 2 4 1 2
(reallocate-step '(3 1 2 3)) ;; 0 2 3 4
(reallocate-step '(0 2 3 4)) ;; 1 3 1 4
(reallocate-step '(1 3 1 4)) ;; 1 3 1 4
(reallocate-step '(4 1 15 12 0 9 9 5 5 8 7 3 14 5 12 3)) ;; 5 2 0 13 1 10 10 6 6 9 8 4 15 6 13 4
(reallocate '(4 1 15 12 0 9 9 5 5 8 7 3 14 5 12 3))
(find-idx-of-max '(7 3 2 19 20)) ;; 4
(cycle-list '(0 2 7 0) 2 2 1) ;; 2 4 1 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment