From cdf29bac8a451008c587fc8a46099144047be15a Mon Sep 17 00:00:00 2001 From: Oscar Najera Date: Mon, 5 Dec 2022 13:03:12 +0100 Subject: [AoC2022] Elisp 05 --- AoC2022/05/solver.el | 45 ++++++++++++++++++++++++++++++--------------- 1 file changed, 30 insertions(+), 15 deletions(-) (limited to 'AoC2022/05/solver.el') 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 -- cgit v1.2.3