From f6174701ace9f37954ac0f71aa41908433540ad6 Mon Sep 17 00:00:00 2001 From: Oscar Najera Date: Thu, 8 Dec 2022 04:42:19 +0100 Subject: [AoC2022] Elisp 07-01 --- AoC2022/07/solver.el | 58 ++++++++++++++++++++++++++++++++++------------------ 1 file changed, 38 insertions(+), 20 deletions(-) diff --git a/AoC2022/07/solver.el b/AoC2022/07/solver.el index ab97c08..38354ff 100644 --- a/AoC2022/07/solver.el +++ b/AoC2022/07/solver.el @@ -6,10 +6,6 @@ ;; Maintainer: Óscar Nájera ;; Created: December 08, 2022 ;; Modified: December 08, 2022 -;; Version: 0.0.1 -;; Keywords: abbrev bib c calendar comm convenience data docs emulations extensions faces files frames games hardware help hypermedia i18n internal languages lisp local maint mail matching mouse multimedia news outlines processes terminals tex tools unix vc wp -;; Homepage: https://github.com/titan/solver -;; Package-Requires: ((emacs "24.3")) ;; ;; This file is not part of GNU Emacs. ;; @@ -22,7 +18,6 @@ (require 'cl-lib) -(with-temp-buffer (insert "$ cd / $ ls dir a @@ -46,24 +41,47 @@ $ ls 8033020 d.log 5626152 d.ext 7214296 k") - (let ((data (split-string (buffer-string) "\n"))) - (cl-labels ((scan () - (cl-loop for item = (pop data) - while (and item (not (string= "$ cd .." item))) - when (parse item) - collect it)) - (parse (entry) - (pcase (split-string entry) - (`("$" "cd" ,dir) (cons dir (scan))) - (`("$" "ls") nil) - (`("dir" ,dir) nil) - (`(,size ,name) (cons name (string-to-number size)))))) - (scan) - ))) +(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 () + (cl-loop for item = (pop lines) + while (and item (not (string= "$ cd .." item))) + when (parse item) + collect it)) + (parse (entry) + (pcase (split-string entry) + (`("$" "cd" ,dir) (cons dir (scan))) + (`("$" "ls") nil) + (`("dir" ,dir) nil) + (`(,size ,name) (cons name (string-to-number size)))))) + + (car (scan)))) +(defun solver-add-dir-size (tree) + (cl-labels ((combiner (tri) + (list (car tri) + (adder tri) + (seq-reduce (lambda (acc item) + (if (numberp (cdr item)) + acc + (cons (combiner item) acc))) + (cdr tri) nil))) + (adder (tri) + (seq-reduce (lambda (acc item) + (+ acc + (if (numberp (cdr item)) + (cdr item) + (adder item)))) + (cdr tri) 0))) + (cl-loop for (_ size) on (flatten-tree (combiner tree)) by #'cddr + when (< size 100000) + sum size))) -(append '(5 6 8) (cons 5 8)) (provide 'solver) ;;; solver.el ends here -- cgit v1.2.3