Skip to content

Commit e18b403

Browse files
committed
2022 - Day 9
1 parent dc7e542 commit e18b403

File tree

3 files changed

+2088
-0
lines changed

3 files changed

+2088
-0
lines changed

python/2022/day9/day9.py

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
from python.download_input import get_input_content
2+
3+
4+
DIRECTIONS = {
5+
'U': (0, -1),
6+
'R': (1, 0),
7+
'D': (0, 1),
8+
'L': (-1, 0),
9+
}
10+
11+
12+
def move_tail(hx: int, hy: int, tx: int, ty: int) -> tuple[int, int]:
13+
if hy == ty:
14+
if hx - tx > 1:
15+
tx += 1
16+
elif hx - tx < -1:
17+
tx -= 1
18+
elif hx == tx:
19+
if hy - ty > 1:
20+
ty += 1
21+
elif hy - ty < -1:
22+
ty -= 1
23+
else:
24+
if hx - tx > 1:
25+
tx += 1
26+
if hy > ty:
27+
ty += 1
28+
else:
29+
ty -= 1
30+
elif hx - tx < -1:
31+
tx -= 1
32+
if hy > ty:
33+
ty += 1
34+
else:
35+
ty -= 1
36+
elif hy - ty > 1:
37+
ty += 1
38+
if hx > tx:
39+
tx += 1
40+
else:
41+
tx -= 1
42+
elif hy - ty < -1:
43+
ty -= 1
44+
if hx > tx:
45+
tx += 1
46+
else:
47+
tx -= 1
48+
49+
return tx, ty
50+
51+
52+
def first(data):
53+
hx, hy, tx, ty = 0, 0, 0, 0
54+
tail_positions = set()
55+
for line in data:
56+
d, v = line.split()
57+
v = int(v)
58+
for _ in range(v):
59+
hx, hy = (hx + DIRECTIONS[d][0], hy + DIRECTIONS[d][1])
60+
tx, ty = move_tail(hx, hy, tx, ty)
61+
tail_positions.add((tx, ty))
62+
63+
return len(tail_positions)
64+
65+
66+
def second(data):
67+
knot_positions = [(0, 0) for _ in range(10)]
68+
tail_positions = set()
69+
for line in data:
70+
d, v = line.split()
71+
v = int(v)
72+
for _ in range(v):
73+
knot_positions[0] = (knot_positions[0][0] + DIRECTIONS[d][0], knot_positions[0][1] + DIRECTIONS[d][1])
74+
for i in range(9):
75+
hx, hy = knot_positions[i]
76+
tx, ty = knot_positions[i+1]
77+
knot_positions[i + 1] = move_tail(hx, hy, tx, ty)
78+
tail_positions.add(knot_positions[-1])
79+
80+
return len(tail_positions)
81+
82+
83+
if __name__ == "__main__":
84+
content = get_input_content(__file__)
85+
86+
print(f'Le résultat de la première partie est :\n{first(content)}')
87+
88+
print(f'Le résultat de la deuxième partie est :\n{second(content)}')

0 commit comments

Comments
 (0)