mirror of
https://github.com/thib8956/advent-of-code.git
synced 2026-06-15 13:38:15 +00:00
2022 day 7 part 2
This commit is contained in:
@@ -45,8 +45,7 @@ def parse_tree(inp):
|
|||||||
return adj
|
return adj
|
||||||
|
|
||||||
|
|
||||||
def main(inp):
|
def calculate_sizes(adj):
|
||||||
adj = parse_tree(inp)
|
|
||||||
# DFS the tree to calculate size of each directory
|
# DFS the tree to calculate size of each directory
|
||||||
stack = [((), adj[()])]
|
stack = [((), adj[()])]
|
||||||
visited = {()}
|
visited = {()}
|
||||||
@@ -58,26 +57,42 @@ def main(inp):
|
|||||||
if isinstance(child, tuple): # file
|
if isinstance(child, tuple): # file
|
||||||
name, size = child
|
name, size = child
|
||||||
sizes[path] += int(size)
|
sizes[path] += int(size)
|
||||||
print(f"file {name} {size}")
|
# print(f"file {name} {size}")
|
||||||
else: # dir
|
else: # dir
|
||||||
child_path = (*path, child)
|
child_path = (*path, child)
|
||||||
print(f"dir {child_path}")
|
# print(f"dir {child_path}")
|
||||||
if child_path not in visited:
|
if child_path not in visited:
|
||||||
visited.add(child_path)
|
visited.add(child_path)
|
||||||
stack.append((child_path, adj[child_path]))
|
stack.append((child_path, adj[child_path]))
|
||||||
dirs.add(child_path)
|
dirs.add(child_path)
|
||||||
|
|
||||||
# Add up sizes of subdirectories to parent directories
|
# Add up sizes of subdirectories to parent directories
|
||||||
for path in sorted(dirs, key=len, reverse=True):
|
for path in sorted(dirs, key=len, reverse=True):
|
||||||
if path: # not root
|
if path: # not root
|
||||||
parent = path[:-1]
|
parent = path[:-1]
|
||||||
sizes[parent] += sizes[path]
|
sizes[parent] += sizes[path]
|
||||||
|
return sizes
|
||||||
|
|
||||||
|
|
||||||
|
def part1(sizes):
|
||||||
total = 0
|
total = 0
|
||||||
for size in sizes.values():
|
for size in sizes.values():
|
||||||
if size <= 100000:
|
if size <= 100000:
|
||||||
total += size
|
total += size
|
||||||
print(total)
|
return total
|
||||||
|
|
||||||
|
|
||||||
|
def part2(sizes):
|
||||||
|
total_space = sizes[()] # size of root
|
||||||
|
needed_space = 30000000 - (70000000 - total_space)
|
||||||
|
candidates = [size for size in sizes.values() if size >= needed_space]
|
||||||
|
return min(candidates)
|
||||||
|
|
||||||
|
|
||||||
|
def main(inp):
|
||||||
|
adj = parse_tree(inp)
|
||||||
|
sizes = calculate_sizes(adj)
|
||||||
|
print("Part 1: ", part1(sizes))
|
||||||
|
print("Part 2: ", part2(sizes))
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
Reference in New Issue
Block a user