blob: 910a81d6799231e281ad6a312130c0049e5c1027 (
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
;;; solver.el --- Day 07 -*- 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 08, 2022
;; Modified: December 08, 2022
;;
;; This file is not part of GNU Emacs.
;;
;;; Commentary:
;;
;; Day 07
;;
;;; Code:
(require 'cl-lib)
(require 'subr-x)
(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))))))
(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-aggregate-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)))
(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
|