advent_of_code/2022/9/9.py

83 lines
1.8 KiB
Python
Raw Normal View History

2023-01-24 02:50:23 +01:00
#!/usr/bin/env python
# 2022 - Advent Of Code 9
import math
# file = 'input_example.txt'
file = 'input.txt'
visited_pos = [[0, 0]]
head_pos = [0, 0]
tail_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):
vx = h[0] - t[0]
vy = h[1] - t[1]
vlen = round(math.sqrt(vx * vx + vy * vy))
head_tail_dist = vlen
# print(f'head_tail_dist: {head_tail_dist}')
if head_tail_dist > 1:
# print('move tail!')
nx = col_round(vx / vlen)
ny = col_round(vy / vlen)
print(f'x:{vx}/{nx} y: {vy}/{ny} len: {vlen}')
t[0] += nx
t[1] += ny
print(f'head_pos: {h}')
print(f'new tail_pos: {t}')
v_list = [t[0], t[1]]
if v_list not in visited_pos:
visited_pos.append(v_list)
# visited_pos.append(v_list)
head_moves = parse_file(file)
print(head_moves)
for m in head_moves:
if m[0] == 'R':
print(f'right: {m[1]}')
for _ in range(0, m[1]):
head_pos[0] += 1
move_tail(head_pos, tail_pos)
if m[0] == 'L':
print(f'left: {m[1]}')
for _ in range(0, m[1]):
head_pos[0] -= 1
move_tail(head_pos, tail_pos)
if m[0] == 'U':
print(f'up: {m[1]}')
for _ in range(0, m[1]):
head_pos[1] += 1
move_tail(head_pos, tail_pos)
if m[0] == 'D':
print(f'down: {m[1]}')
for _ in range(0, m[1]):
head_pos[1] -= 1
move_tail(head_pos, tail_pos)
print(visited_pos)
print(len(visited_pos))