You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.4 KiB
53 lines
1.4 KiB
#!/usr/bin/env python3
|
|
|
|
import sys
|
|
|
|
def move_head(m,h):
|
|
hx, hy = h
|
|
if m == 'R': hx = hx + 1
|
|
elif m == 'L': hx = hx - 1
|
|
elif m == 'U': hy = hy + 1
|
|
elif m == 'D': hy = hy - 1
|
|
return hx,hy
|
|
|
|
def follow(h,t):
|
|
hx, hy = h
|
|
tx, ty = t
|
|
if abs(hx - tx) > 1 or abs(hy - ty) > 1:
|
|
if hy == ty: tx = (tx+1) if hx>tx else (tx-1)
|
|
elif hx == tx: ty = (ty+1) if hy>ty else (ty-1)
|
|
else:
|
|
tx = (tx+1) if hx>tx else (tx-1)
|
|
ty = (ty+1) if hy>ty else (ty-1)
|
|
return (hx, hy), (tx, ty)
|
|
|
|
if __name__ == '__main__':
|
|
moves = [tuple(line.strip('\n').split(' ')) for line in open(sys.argv[1])]
|
|
head = (0,0)
|
|
tail = (0,0)
|
|
tail_pos = set([(0,0)])
|
|
|
|
# challenge 1
|
|
for m in moves:
|
|
mov, num = m
|
|
num = int(num)
|
|
for _ in range(num):
|
|
head = move_head(mov,head)
|
|
head, tail = follow(head,tail)
|
|
tail_pos.add(tail)
|
|
res1 = str(len(tail_pos))
|
|
print("challenge 1:" + "\n" + res1 + "\n")
|
|
|
|
# challenge 2
|
|
ropes = [(0,0)] * 10
|
|
tail_pos = set([(0,0)])
|
|
for m in moves:
|
|
mov, num = m
|
|
num = int(num)
|
|
for _ in range(num):
|
|
ropes[0] = move_head(mov,ropes[0])
|
|
for i in range(len(ropes)-1): ropes[i], ropes[i+1] = follow(ropes[i],ropes[i+1])
|
|
tail_pos.add(ropes[9])
|
|
res2 = str(len(tail_pos))
|
|
print("challenge 2:" + "\n" + res2 + "\n")
|
|
|
|
|