-
Notifications
You must be signed in to change notification settings - Fork 0
/
day12_2.py
64 lines (49 loc) · 1.8 KB
/
day12_2.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
def rotate_left(coordinates, degree):
for _ in range(degree):
coordinates[0], coordinates[1] = coordinates[1], -1 * coordinates[0]
return coordinates
def rotate_right(coordinates, degree):
for _ in range(degree):
coordinates[0], coordinates[1] = -1 * coordinates[1], coordinates[0]
return coordinates
def step(coordinates, direction, distance):
if direction == 'N':
coordinates[0] += distance
if direction == 'S':
coordinates[0] -= distance
if direction == 'E':
coordinates[1] += distance
if direction == 'W':
coordinates[1] -= distance
return coordinates
def navigate(instructions):
coordinates = [0, 0]
waypoint_coordinates = [1, 10]
for i in instructions:
if i[0] in 'NSEW':
waypoint_coordinates = step(waypoint_coordinates, i[0], i[1])
elif i[0] == 'L':
degree = i[1] // 90
waypoint_coordinates = rotate_left(waypoint_coordinates, degree)
elif i[0] == 'R':
degree = i[1] // 90
waypoint_coordinates = rotate_right(waypoint_coordinates, degree)
elif i[0] == 'F':
for _ in range(i[1]):
coordinates = step(coordinates, 'N', waypoint_coordinates[0])
coordinates = step(coordinates, 'E', waypoint_coordinates[1])
else:
raise ValueError("Unknown instruction {}".format(i[0]))
return coordinates
def part2():
with open("input12.txt") as file:
instructions = [(line[0], int(line[1:])) for line in file]
result = navigate(instructions)
print(result)
return result
part2()
def test_navigate():
instructions = [('F', 10), ('N', 3), ('F', 7), ('R', 90), ('F', 11)]
result = navigate(instructions)
assert result[0] == -72
assert result[1] == 214