From c3cf19fc1ff67d89d69eb80e974bc330daebb202 Mon Sep 17 00:00:00 2001 From: Oscar Najera Date: Thu, 8 Dec 2022 14:16:07 +0100 Subject: [AoC2022] Elisp 07 --- AoC2022/07/solver.el | 58 ++++++++++++++++++++++++---------------------------- 1 file changed, 27 insertions(+), 31 deletions(-) (limited to 'AoC2022') diff --git a/AoC2022/07/solver.el b/AoC2022/07/solver.el index 38354ff..910a81d 100644 --- a/AoC2022/07/solver.el +++ b/AoC2022/07/solver.el @@ -17,35 +17,23 @@ (require 'cl-lib) +(require 'subr-x) - (insert "$ cd / -$ ls -dir a -14848514 b.txt -8504156 c.dat -dir d -$ cd a -$ ls -dir e -29116 f -2557 g -62596 h.lst -$ cd e -$ ls -584 i -$ cd .. -$ cd .. -$ cd d -$ ls -4060174 j -8033020 d.log -5626152 d.ext -7214296 k") +(ert-deftest test-solver () + (with-temp-buffer + (insert-file-contents "input") + (let* ((dir-sizes + (thread-first + (split-string (buffer-string) "\n") + (solver-parse-listing) + (solver-aggregate-size))) + (total-disk 70000000) + (free-disk (- total-disk (cadr dir-sizes))) + (needed 30000000) + (to-free (- needed free-disk))) + (should (= 1845346 (solver-add-dir-size dir-sizes))) + (should (= 3636703 (solver-delete-what dir-sizes to-free)))))) -(with-temp-buffer - (insert-file-contents "input") - (solver-add-dir-size - (solver-parse-listing (split-string (buffer-string) "\n")))) (defun solver-parse-listing (lines) (cl-labels ((scan () @@ -62,7 +50,7 @@ $ ls (car (scan)))) -(defun solver-add-dir-size (tree) +(defun solver-aggregate-size (tree) (cl-labels ((combiner (tri) (list (car tri) (adder tri) @@ -79,9 +67,17 @@ $ ls (adder item)))) (cdr tri) 0))) - (cl-loop for (_ size) on (flatten-tree (combiner tree)) by #'cddr - when (< size 100000) - sum size))) + (flatten-tree (combiner tree)))) + +(defun solver-add-dir-size (sizes) + (cl-loop for (_ size) on sizes by #'cddr + when (< size 100000) + sum size)) + +(defun solver-delete-what (sizes required) + (cl-loop for (_ size) on sizes by #'cddr + when (> size required) + minimizing size)) (provide 'solver) ;;; solver.el ends here -- cgit v1.2.3