-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path__init__.py
More file actions
110 lines (80 loc) · 2.57 KB
/
__init__.py
File metadata and controls
110 lines (80 loc) · 2.57 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
from typing import *
from dataclasses import dataclass
from aocpy import BaseChallenge
class Path:
parts: List[str]
def __init__(self):
self.parts = []
def cd(self, arg: str):
if arg == "..":
_ = self.parts.pop()
elif arg != ".":
self.parts.append(arg)
def cwd(self) -> str:
x = "/".join(self.parts)
return x if len(x) != 0 else "/"
def abs_in_cwd(self, path: str) -> str:
cwd = self.cwd()
if cwd == "/":
return "/" + path
return cwd + "/" + path
@dataclass(init=False)
class Directories:
directory_names: List[str]
files: Dict[str, int]
def __init__(self):
self.directory_names = []
self.files = {}
def add_dir(self, path: str):
if path not in self.directory_names:
self.directory_names.append(path)
def add_file(self, path: str, size: int):
self.files[path] = size
def parse(instr: str) -> Directories:
dirs = Directories()
fp = Path()
i = 0
lines = instr.strip().splitlines()
while i < len(lines):
line = lines[i]
if line.startswith("$ cd"):
fp.cd(line.removeprefix("$ cd "))
dirs.add_dir(fp.cwd())
elif line.startswith("$ ls"):
while i < len(lines) - 1 and not lines[i + 1].startswith("$"):
i += 1
line = lines[i]
sp = line.split(" ")
if sp[0] == "dir":
dirs.add_dir(fp.abs_in_cwd(sp[1]))
else:
dirs.add_file(fp.abs_in_cwd(sp[1]), int(sp[0]))
i += 1
return dirs
def calculate_directory_size(dirs: Directories, target_dir_name: str) -> int:
total = 0
for fname in dirs.files:
if fname.startswith(target_dir_name + "/"):
total += dirs.files[fname]
return total
class Challenge(BaseChallenge):
@staticmethod
def one(instr: str) -> int:
dirs = parse(instr)
total = 0
for dir_name in dirs.directory_names:
sz = calculate_directory_size(dirs, dir_name)
if sz <= 100000:
total += sz
return total
@staticmethod
def two(instr: str) -> int:
dirs = parse(instr)
used = 70000000 - calculate_directory_size(dirs, "")
amount_to_delete = 30000000 - used
opts = []
for dir_name in dirs.directory_names:
sz = calculate_directory_size(dirs, dir_name)
if sz >= amount_to_delete:
opts.append(sz)
return min(opts)