61 lines
1.4 KiB
Python
Executable File
61 lines
1.4 KiB
Python
Executable File
#!/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))
|