This commit is contained in:
parent
c20b3d31e9
commit
101f8618c9
2 changed files with 89 additions and 0 deletions
81
2022/9/9_2.py
Normal file
81
2022/9/9_2.py
Normal file
|
@ -0,0 +1,81 @@
|
|||
#!/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))
|
8
2022/9/input_example2.txt
Normal file
8
2022/9/input_example2.txt
Normal file
|
@ -0,0 +1,8 @@
|
|||
R 5
|
||||
U 8
|
||||
L 8
|
||||
D 3
|
||||
R 17
|
||||
D 10
|
||||
L 25
|
||||
U 20
|
Loading…
Reference in a new issue