81 lines
1.7 KiB
Python
81 lines
1.7 KiB
Python
#!/usr/bin/env python
|
|
# 2022 - Advent Of Code 9 part2
|
|
|
|
import math
|
|
|
|
# file = 'input_example.txt'
|
|
# file = 'input_example2.txt'
|
|
file = 'input.txt'
|
|
|
|
|
|
visited_pos = [[0, 0]]
|
|
|
|
|
|
def parse_file(input_file):
|
|
moves = []
|
|
with open(input_file, encoding="utf-8") as f:
|
|
for line in f.readlines():
|
|
d, u = line.strip().split(' ')
|
|
moves.append((d, int(u)))
|
|
return moves
|
|
|
|
|
|
def col_round(x):
|
|
frac = x - int(x)
|
|
if frac < 0.5:
|
|
return math.floor(x)
|
|
return math.ceil(x)
|
|
|
|
|
|
def move_tail(h, t, i):
|
|
vx = h[0] - t[0]
|
|
vy = h[1] - t[1]
|
|
|
|
vlen = round(math.sqrt(vx * vx + vy * vy))
|
|
head_tail_dist = vlen
|
|
|
|
if head_tail_dist > 1:
|
|
nx = col_round(vx / vlen)
|
|
ny = col_round(vy / vlen)
|
|
t[0] += nx
|
|
t[1] += ny
|
|
if i == 9:
|
|
v_list = [t[0], t[1]]
|
|
if v_list not in visited_pos:
|
|
visited_pos.append(v_list)
|
|
|
|
|
|
def move_rope(r):
|
|
for i in range(1, 10):
|
|
move_tail(r[i-1], r[i], i)
|
|
|
|
|
|
head_moves = parse_file(file)
|
|
print(head_moves)
|
|
rope = [[0, 0] for _ in range(0, 10)]
|
|
|
|
|
|
for m in head_moves:
|
|
if m[0] == 'R':
|
|
print(f'right: {m[1]}')
|
|
for _ in range(0, m[1]):
|
|
rope[0][0] += 1
|
|
move_rope(rope)
|
|
if m[0] == 'L':
|
|
print(f'left: {m[1]}')
|
|
for _ in range(0, m[1]):
|
|
rope[0][0] -= 1
|
|
move_rope(rope)
|
|
if m[0] == 'U':
|
|
print(f'up: {m[1]}')
|
|
for _ in range(0, m[1]):
|
|
rope[0][1] += 1
|
|
move_rope(rope)
|
|
if m[0] == 'D':
|
|
print(f'down: {m[1]}')
|
|
for _ in range(0, m[1]):
|
|
rope[0][1] -= 1
|
|
move_rope(rope)
|
|
|
|
print(visited_pos)
|
|
print(len(visited_pos))
|