Advent of Code 2022 - 9

Day 9: Rope Bridge

https://adventofcode.com/2022/day/9

1
2
3
4
5
6
7
8
9
10
with open('09.txt', 'r') as fp:
lines = fp.readlines()
motions = [line.strip().split() for line in lines]

move = {
'U': [0, 1],
'D': [0, -1],
'L': [-1, 0],
'R': [1, 0],
}

Part One

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
visited = set()
hx, hy = 0, 0
tx, ty = 0, 0
for m in motions:
dir, step = m
step = int(step)
for i in range(step):
hx = hx + move[dir][0]
hy = hy + move[dir][1]
dx = hx - tx
dy = hy - ty
if abs(dx) >= 2 or abs(dy) >= 2:
tx += int(dx>0) - int(dx<0)
ty += int(dy>0) - int(dy<0)
visited.add((tx, ty))
print(len(visited))

Answer: 6332

Part Two

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
visited = set()
hx, hy = 0, 0
tx, ty = 0, 0
rope = [(0, 0)] * 10
for m in motions:
dir, step = m
step = int(step)
for i in range(step):
hx, hy = rope[0]
hx = hx + move[dir][0]
hy = hy + move[dir][1]
rope[0] = (hx, hy)
for j in range(len(rope)-1):
hx, hy = rope[j]
tx, ty = rope[j+1]
dx = hx - tx
dy = hy - ty
if abs(dx) >= 2 or abs(dy) >= 2:
tx += int(dx>0) - int(dx<0)
ty += int(dy>0) - int(dy<0)
rope[j+1] = (tx, ty)
visited.add(rope[-1])
print(len(visited))

Answer: 2511