Created
December 7, 2019 06:23
-
-
Save egnha/a488a4b9b313fb916d838a4c65ba2066 to your computer and use it in GitHub Desktop.
Advent of Code 2019 (Day 6, Part 1)
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
""" | |
Advent of Code 2019: Day 6, Part 1 | |
""" | |
from collections import defaultdict | |
tree = defaultdict(list) | |
with open("06-input.txt") as f: | |
for line in f.readlines(): | |
tree[line[:3]].append(line[4:7]) | |
# checksum = sum(k * #(nodes at depth k): nodes at depth k, k = 1, 2, ...) | |
# "Depth" means distance from root node ("COM"). | |
checksum, depth = 0, 1 | |
nodes = ["COM"] | |
# Prune nodes of increasing depth from tree. | |
while tree: | |
next_nodes = [] | |
for node in nodes: | |
children = tree.pop(node, []) | |
checksum += depth * len(children) | |
next_nodes.extend(children) | |
nodes = next_nodes | |
depth += 1 | |
print(checksum) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment