aboutsummaryrefslogtreecommitdiffstats
path: root/AoC2022/05/solver.el
blob: b81e4be8eeea6ac2404ff86f5dc4a307a71b2615 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
;;; solver.el --- Day 05 -*- lexical-binding: t; -*-
;;
;; Copyright (C) 2022 Óscar Nájera
;;
;; Author: Óscar Nájera <hi@oscarnajera.com>
;; Maintainer: Óscar Nájera <hi@oscarnajera.com>
;; Created: December 05, 2022
;; Modified: December 05, 2022
;;
;; This file is not part of GNU Emacs.
;;
;;; Commentary:
;;
;;  Day 05
;;
;;; Code:
(require 'subr-x)
(require 'cl-lib)

(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-apply-moves! (mover-f 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)))))
      (setf (aref stacks to)
            (append (funcall mover-f (seq-take (aref stacks from) amount))
                    (aref stacks to)))
      (setf (aref stacks from) (seq-drop (aref stacks from) amount))))
  stacks)

(defun solver (bulkp)
  (with-temp-buffer
    (insert-file-contents "input")
    (re-search-forward "^ 1")
    (thread-last
      (solver-build-stacks)
      (solver-apply-moves! (if bulkp #'identity #'reverse))
      (cl-map 'string #'car))))

(ert-deftest solver-solutions ()
  (should (equal "TPGVQPFDH"
                 (solver nil)))
  (should (equal "DMRDFRHHH"
                 (solver t))))


(provide 'solver)
;;; solver.el ends here