Last active
December 8, 2022 03:38
-
-
Save dstandish/6b178c332f044ee7a015cd491e467938 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import annotations | |
from aocd import lines, numbers | |
class Node: | |
def __init__(self, name, type, size=0): | |
self.name = name | |
self.type = type | |
self.size = size | |
self.children = [] | |
def __repr__(self): | |
return f"{self.name=}, {self.type=}, {self.size=}, {self.children=}" | |
def total_size(self): | |
val = self.size | |
for n in self.children: | |
val += n.total_size() | |
return val | |
stack = [] | |
nodes = [] | |
for line in lines: | |
if line == "$ cd ..": | |
stack.pop() | |
continue | |
elif line.startswith("$ cd"): | |
name = line[5:] | |
node = Node(name, type="dir") | |
if stack: | |
stack[-1].children.append(node) | |
stack.append(node) | |
nodes.append(node) | |
continue | |
elif line.startswith("$ ls"): | |
continue | |
elif line.startswith("dir"): | |
continue | |
else: | |
size, name = line.split() | |
node = Node(name=name, type="file", size=int(size)) | |
stack[-1].children.append(node) | |
nodes.append(node) | |
curr = nodes[0].total_size() | |
free = 70000000 - curr | |
needed = 30000000 - free | |
print(sorted((n.total_size() for n in nodes if n.total_size() >= needed and n.type == "dir"))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment