-
Notifications
You must be signed in to change notification settings - Fork 0
/
9.py
72 lines (61 loc) · 1.82 KB
/
9.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
#!/usr/bin/python3
class Knot:
def __init__(self):
self.x = 0
self.y = 0
@property
def pos(self):
return self.x, self.y
class Head(Knot):
def step(self, direction):
# move 1 step in the direction
match direction:
case 'U':
self.y += 1
case 'D':
self.y -= 1
case 'L':
self.x -= 1
case 'R':
self.x += 1
class Tail(Knot):
def __init__(self):
super().__init__()
self.history = set()
def follow(self, pos):
x, y = pos
dist_x = x - self.x
dist_y = y - self.y
if abs(dist_x) == 2 and not dist_y: # horizontal
xv = 1 if dist_x > 0 else -1
self.x += xv
elif abs(dist_y) == 2 and not dist_x: # vertical
yv = 1 if dist_y > 0 else -1
self.y += yv
elif (abs(dist_y) == 2 and abs(dist_x) in (1, 2)) or (abs(dist_x) == 2 and abs(dist_y) in (1, 2)):
xv = 1 if dist_x > 0 else -1
self.x += xv
yv = 1 if dist_y > 0 else -1
self.y += yv
self.history.add((self.x, self.y))
head = Head()
tail = Tail()
with open('9.input') as f:
directions = f.read().splitlines()
for direction in directions:
dir_, steps = direction.split()
for _ in range(int(steps)):
head.step(dir_)
tail.follow(head.pos)
print(f"Number of positions visited: {len(tail.history)}")
# part 2
head = Head()
tails = [Tail() for _ in range(9)]
for direction in directions:
dir_, steps = direction.split()
for _ in range(int(steps)):
head.step(dir_)
tails[0].follow(head.pos)
for i in range(1, 9):
tails[i].follow(tails[i-1].pos)
print(f"Number of positions visited: {len(tails[8].history)}")