-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart_two.py
69 lines (48 loc) · 1.57 KB
/
part_two.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from typing import override
from infrastructure.solutions.base import Solution
MOVE = tuple[str, int]
class Year2016Day1Part2Solution(Solution):
@classmethod
@override
def parse_input(cls, text_input: str) -> dict[str, list[MOVE]]:
moves = []
for line in text_input.split(', '):
# R2 or L43 formats
direction = line[0]
steps = int(line[1:])
moves.append((direction, int(steps)))
return {'moves': moves}
@classmethod
@override
def solve(cls, moves: list[MOVE]) -> int:
"""
Time: O(n*m)
Space: O(n*m)
Where n - number of moves,
m - maximum steps per move
"""
x = 0
y = 0
dx = 0
dy = 1
seen = {(x, y)}
first_x_duplicate = None
first_y_duplicate = None
for direction, steps in moves:
if first_x_duplicate is not None and first_y_duplicate is not None:
break
if direction == 'L':
dx, dy = -dy, dx
if direction == 'R':
dx, dy = dy, -dx
for _ in range(steps):
x += dx
y += dy
if (x, y) in seen and first_x_duplicate is None and first_y_duplicate is None:
first_x_duplicate = x
first_y_duplicate = y
break
seen.add((x, y))
return abs(first_x_duplicate) + abs(first_y_duplicate)
if __name__ == '__main__':
print(Year2016Day1Part2Solution.main())