-
Notifications
You must be signed in to change notification settings - Fork 2
/
aoc201712.py
85 lines (61 loc) · 1.95 KB
/
aoc201712.py
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
"""AoC 12, 2017: Digital Plumber."""
# Standard library imports
import pathlib
import sys
def parse_data(puzzle_input):
"""Parse input."""
return dict(parse_pipe(line) for line in puzzle_input.split("\n"))
def parse_pipe(pipe):
"""Parse a line describing pipes from one program to others.
>>> parse_pipe("1 <-> 1")
(1, [1])
>>> parse_pipe("3 <-> 2, 4")
(3, [2, 4])
"""
from_id, _, to_id = pipe.partition(" <-> ")
return int(from_id), [int(id) for id in to_id.split(", ")]
def part1(data):
"""Solve part 1."""
return len(find_cluster(data, root_id=0))
def part2(data):
"""Solve part 2."""
return len(find_clusters(data))
def find_cluster(pipes, root_id):
"""Find cluster containing root.
>>> cluster = find_cluster({0: [1, 2], 1: [0, 2], 2: [0, 1], 3: [3]}, 0)
>>> sorted(cluster)
[0, 1, 2]
>>> find_cluster({0: [1, 2], 1: [0, 2], 2: [0, 1], 3: [3]}, 3)
{3}
"""
cluster = {root_id}
to_add = set(pipes[root_id])
while to_add:
id = to_add.pop()
cluster.add(id)
to_add |= set(pipes[id]) - cluster
return cluster
def find_clusters(pipes):
"""Find all clusters.
>>> clusters = find_clusters({0: [1, 2], 1: [0, 2], 2: [0, 1], 3: [3]})
>>> [sorted(cluster) for cluster in clusters]
[[0, 1, 2], [3]]
"""
clusters = []
remaining_roots = set(pipes)
while remaining_roots:
root_id = remaining_roots.pop()
cluster = find_cluster(pipes, root_id)
remaining_roots -= cluster
clusters.append(cluster)
return clusters
def solve(puzzle_input):
"""Solve the puzzle for the given input."""
data = parse_data(puzzle_input)
yield part1(data)
yield part2(data)
if __name__ == "__main__":
for path in sys.argv[1:]:
print(f"\n{path}:")
solutions = solve(puzzle_input=pathlib.Path(path).read_text().strip())
print("\n".join(str(solution) for solution in solutions))