diff options
Diffstat (limited to 'AoC2022/05')
-rw-r--r-- | AoC2022/05/solver.el | 45 |
1 files changed, 30 insertions, 15 deletions
diff --git a/AoC2022/05/solver.el b/AoC2022/05/solver.el index 59faf65..edcd7cc 100644 --- a/AoC2022/05/solver.el +++ b/AoC2022/05/solver.el @@ -15,36 +15,51 @@ ;; ;;; Code: (require 'subr-x) + (defun solver-build-stacks () (let* ((stacks-len (length (split-string (buffer-substring-no-properties (line-beginning-position) (line-end-position))))) (stacks (make-vector stacks-len nil)) next) - (message "%S" (list stacks-len (split-string - (buffer-substring-no-properties (point) (line-end-position))))) - (while (setq next (search-backward "]" nil t)) (push (intern (string (char-before))) (aref stacks (/ (- next (line-beginning-position) 1) 4)))) stacks)) -(defun solver-apply-moves (stacks) +(defun solver-single-move! (stacks amount from to) + (dotimes (_ amount) + (push (pop (aref stacks from)) (aref stacks to)))) + +(defun solver-bulk-move! (stacks amount from to) + (setf (aref stacks to) + (append (seq-take (aref stacks from) amount) + (aref stacks to))) + (setf (aref stacks from) (seq-drop (aref stacks from) amount))) + +(defun solver-apply-moves (execution stacks) (while (re-search-forward (rx bol "move " (group (+ digit)) " from " (group (+ digit)) " to " (group (+ digit))) nil t) - (let ((from (1- (string-to-number (match-string 2)))) + (let ((amount (string-to-number (match-string 1))) + (from (1- (string-to-number (match-string 2)))) (to (1- (string-to-number (match-string 3))))) - (dotimes (_ (string-to-number (match-string 1))) - (push (pop (aref stacks from)) (aref stacks to))))) + (funcall execution stacks amount from to))) stacks) -'(T P G V Q P F D H) -(with-temp-buffer - (insert-file-contents "input") - (re-search-forward "^ 1") - (thread-last - (solver-build-stacks) - (solver-apply-moves) - (seq-map #'car))) +(defun solver (execution) + (with-temp-buffer + (insert-file-contents "input") + (re-search-forward "^ 1") + (thread-last + (solver-build-stacks) + (solver-apply-moves execution) + (seq-map #'car)))) + +(ert-deftest solver-solutions () + (should (equal '(T P G V Q P F D H) + (solver #'solver-single-move!))) + (should (equal '(D M R D F R H H H) + (solver #'solver-bulk-move!)))) + (provide 'solver) ;;; solver.el ends here |