AdventOfCode/2022/day09.py

34 lines
1.1 KiB
Python
Raw Permalink Normal View History

2022-12-09 17:00:35 +10:30
from helpers import *
lines = read_day(9).split('\n')
2022-12-09 16:39:00 +10:30
2022-12-09 17:00:35 +10:30
def move_tail(rope: ArrayLike):
2022-12-09 16:39:00 +10:30
for i in range(1, rope.shape[0]):
2022-12-09 17:00:35 +10:30
delta = rope[i-1] - rope[i]
abs_delta = abs(delta)
if (abs_delta.max() > 1 and abs_delta.min() == 0) or (sum(abs_delta) > 2):
rope[i] += np.sign(delta)
2022-12-09 16:39:00 +10:30
def simulate_rope_drag(length: int, lines: list[str]):
rope = np.zeros([length,2], dtype=dtype)
2022-12-09 17:00:35 +10:30
visited = {tuple(rope[-1])}
2022-12-09 16:39:00 +10:30
for line in lines:
dir_vector = directions_dict[line[0]]
amount = int(line[2:])
for i in range(amount):
2022-12-09 17:00:35 +10:30
rope[0] += dir_vector
2022-12-09 16:39:00 +10:30
move_tail(rope)
2022-12-09 17:00:35 +10:30
visited.add(tuple(rope[-1]))
2022-12-09 16:39:00 +10:30
return visited
visited_part_1 = simulate_rope_drag(2, lines)
print(f'Part 1: String length of 2 - tail visits {len(visited_part_1)} cells')
visited_part_2 = simulate_rope_drag(10, lines)
print(f'Part 2: String length of 10 - tail visits {len(visited_part_2)} cells')
if input('Visualise part 1 cells? [y/N]: ').lower() == 'y':
2022-12-09 17:00:35 +10:30
visualise_sparse_cells_set(visited_part_1, 70)
2022-12-09 16:39:00 +10:30
print()
if input('Visualise part 2 cells? [y/N]: ').lower() == 'y':
2022-12-09 17:00:35 +10:30
visualise_sparse_cells_set(visited_part_2, 70)