2022 day 9

This commit is contained in:
2022-12-09 23:39:01 +00:00
parent 4de4e05050
commit c474e4b25e
4 changed files with 2102 additions and 2 deletions

60
2022/09/part2 Executable file
View File

@@ -0,0 +1,60 @@
#!/usr/bin/env python
import math
MOVES = {
'U': ( 0, -1),
'D': ( 0, +1),
'L': (-1, 0),
'R': (+1, 0),
}
TAIL_POSITIONS = set([])
HEAD = (0, 0)
TAILS = [(0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]
def point_add(a, b):
return tuple(map(lambda i, j: i + j, a, b))
def move(delta):
global TAIL_POSITIONS, HEAD, TAIL
HEAD = point_add(HEAD, delta)
leader = HEAD
for idx, tail in enumerate(TAILS):
ed = math.dist(leader, tail);
if ed < 2.0:
_ # do nothing
elif ed == 2.0: # follow the leader: linear
x, y = 0,0
if leader[0] < tail[0]:
x = -1
elif leader[0] > tail[0]:
x = 1
if leader[1] < tail[1]:
y = -1
elif leader[1] > tail[1]:
y = 1
TAILS[idx] = point_add(tail, (x,y))
else: # follow the leader: diagonal
x, y = 1, 1
if leader[0] < tail[0]:
x = -1
if leader[1] < tail[1]:
y = -1
TAILS[idx] = point_add(tail, (x,y))
leader = TAILS[idx]
TAIL_POSITIONS.add(TAILS[-1])
with open('input') as f:
for line in f:
direction, count = line.rstrip().split(" ")
for _ in range(int(count)):
move(MOVES[direction])
print(len(TAIL_POSITIONS))