]> git.friedersdorff.com Git - max/aoc_2022.git/blob - 7.py
Do day 7
[max/aoc_2022.git] / 7.py
1 """Pretend we're du"""
2 import pprint
3 import sys
4
5
6 """
7 fs = {
8     "dir /": 0,
9     "/siten": 34987,
10     "/itee": 3478,
11     "/esntien": 38787,
12     "dir /a": 0,
13     "/aiensten": 378,
14     "/a/iensent": 1097,
15     "/a/b/c/d/e/g/fensteinsrteni": 347347,
16     "dir /a/b": 0,
17 }
18 """
19
20
21 def populate_dir_sizes(fs):
22     for path, size in fs.items():
23         if path.startswith("dir "):
24             parent = path.split(" ")[1]
25             if parent == "/":
26                 parent = ""
27
28             for child_path, child_size in fs.items():
29                 if child_path.startswith(f"{parent}/"):
30                     fs[path] += child_size
31
32     return fs
33
34
35 fs = {"dir /": 0}
36 current_path = []
37
38 with open("7.in") as fh:
39     for line in fh:
40         line = line.strip()
41
42         if line.startswith("$ cd "):
43             if line[5:] == "/":
44                 current_path = [""]
45             elif line[5:] == "..":
46                 current_path.pop()
47             else:
48                 current_path.append(line[5:])
49
50             continue
51
52         if line.startswith("$ ls"):
53             continue
54
55         size, name = line.split(" ")
56         if size == "dir":
57             fs[f"dir {'/'.join(current_path + [name])}"] = 0
58         else:
59             fs["/".join(current_path + [name])] = int(size)
60
61 fs = populate_dir_sizes(fs)
62
63
64 total_size = 0
65 for path, size in fs.items():
66     if path.startswith("dir ") and size <= 100000:
67         total_size += size
68
69
70 print(total_size)
71
72
73 fs_size = fs["dir /"]
74 disk_size = 70000000
75 update_size = 30000000
76 remaining_disk_space = disk_size - fs_size
77 extra_space_required = update_size - remaining_disk_space
78
79 candidates_for_deletion = []
80 for path, size in fs.items():
81     if path.startswith("dir ") and size >= extra_space_required:
82         candidates_for_deletion.append((path, size))
83
84 candidates_for_deletion.sort(key=lambda x: x[1])
85 print(candidates_for_deletion[0])