;;; solver.el --- Day 05 -*- lexical-binding: t; -*- ;; ;; Copyright (C) 2022 Óscar Nájera ;; ;; Author: Óscar Nájera ;; Maintainer: Óscar Nájera ;; Created: December 05, 2022 ;; Modified: December 05, 2022 ;; ;; This file is not part of GNU Emacs. ;; ;;; Commentary: ;; ;; Day 05 ;; ;;; 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) (while (setq next (search-backward "]" nil t)) (push (char-before) (aref stacks (/ (- next (line-beginning-position) 1) 4)))) 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 ((amount (string-to-number (match-string 1))) (from (1- (string-to-number (match-string 2)))) (to (1- (string-to-number (match-string 3))))) (funcall execution stacks amount from to))) stacks) (defun solver (execution) (with-temp-buffer (insert-file-contents "input") (re-search-forward "^ 1") (thread-last (solver-build-stacks) (solver-apply-moves execution) (cl-map 'string #'car)))) (ert-deftest solver-solutions () (should (equal "TPGVQPFDH" (solver #'solver-single-move!))) (should (equal "DMRDFRHHH" (solver #'solver-bulk-move!)))) (provide 'solver) ;;; solver.el ends here