-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaoc2020_day12.py
75 lines (54 loc) · 1.84 KB
/
aoc2020_day12.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
70
71
72
73
74
75
"""
Advent of Code 2020
Day 12: Rain Risk
"""
DIRS = {"N": (0, +1), "S": (0, -1), "E": (+1, 0), "W": (-1, 0)}
ROTATE = {"L": lambda x, y: (-y, x), "R": lambda x, y: (y, -x)}
def read_puzzle_input(file_name):
with open(file_name, "r") as data_file:
return [(line[0], int(line[1:])) for line in data_file.read().splitlines()]
def day12_part1(data):
x, y = 0, 0
direction = DIRS["E"]
for inst, arg in data:
if inst in DIRS:
dx, dy = DIRS[inst]
x += dx * arg
y += dy * arg
elif inst in ROTATE:
for _ in range(arg % 360 // 90):
direction = ROTATE[inst](*direction)
elif inst == "F":
dx, dy = direction
x += dx * arg
y += dy * arg
return abs(x) + abs(y)
def day12_part2(data):
x, y = 0, 0
wx, wy = 10, 1
for inst, arg in data:
if inst in DIRS:
dx, dy = DIRS[inst]
wx += dx * arg
wy += dy * arg
elif inst in ROTATE:
for _ in range(arg % 360 // 90):
wx, wy = ROTATE[inst](wx, wy)
elif inst == "F":
x += wx * arg
y += wy * arg
return abs(x) + abs(y)
if __name__ == "__main__":
input_data = read_puzzle_input("data/day12.txt")
# Part 1
print("Part 1: What is the Manhattan distance between that location and the ship's starting position?")
print(day12_part1(input_data)) # Correct answer is 820
# Part 2
print("Part 2: What is the Manhattan distance between that location and the ship's starting position?")
print(day12_part2(input_data)) # Correct answer is 66614
# Test cases
test_data = read_puzzle_input("data/day12_test.txt")
def test_day12_part1():
assert day12_part1(test_data) == 25
def test_day12_part2():
assert day12_part2(test_data) == 286