Repository navigation
Expand file tree
/
Copy path08.py
More file actions
66 lines (54 loc) · 1.37 KB
/
Copy path08.py
File metadata and controls
66 lines (54 loc) · 1.37 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
import sys
import pytest
from pathlib import Path
from textwrap import dedent
def solve(text: str) -> int:
lines = text.splitlines()
directions = lines[0]
nodes = {}
for line in lines[2:]:
node, _, neighbors = line.split(maxsplit=2)
neighbors = neighbors[1:-1].split(", ")
nodes[node] = neighbors
current_node = "AAA"
direction_index = 0
total = 0
while current_node != "ZZZ":
neighbors = nodes[current_node]
direction = 0 if directions[direction_index] == "L" else 1
current_node = neighbors[direction]
direction_index = (direction_index + 1) % len(directions)
total += 1
return total
if __name__ == "__main__":
p = Path(sys.argv[1])
print(solve(p.read_text()))
def test():
text = dedent(
"""
RL
AAA = (BBB, CCC)
BBB = (DDD, EEE)
CCC = (ZZZ, GGG)
DDD = (DDD, DDD)
EEE = (EEE, EEE)
GGG = (GGG, GGG)
ZZZ = (ZZZ, ZZZ)
"""
).strip()
assert solve(text) == 2
text = dedent(
"""
LLR
AAA = (BBB, BBB)
BBB = (AAA, ZZZ)
ZZZ = (ZZZ, ZZZ)
"""
).strip()
assert solve(text) == 6
def test_input():
p = Path("08.txt")
if not p.exists():
pytest.skip(f"{p} does not exist")
text = p.read_text()
assert solve(text) == 21409