-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday2.py
58 lines (48 loc) · 1.72 KB
/
day2.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
# navigate accoring to a list of given commands
def navigate(commands):
horizontal = 0
depth = 0
for command in commands:
tokens = command.split(' ')
if tokens[0] == 'forward':
horizontal += int(tokens[1])
elif tokens[0] == 'down':
depth += int(tokens[1])
elif tokens[0] == 'up':
depth -= int(tokens[1])
return {'horizontal': horizontal, 'depth': depth}
# navigate accoring to a list of given commands with aim
def navigate_with_aim(commands):
horizontal = 0
depth = 0
aim = 0
for command in commands:
tokens = command.split(' ')
if tokens[0] == 'forward':
horizontal += int(tokens[1])
depth += aim * int(tokens[1])
elif tokens[0] == 'down':
aim += int(tokens[1])
elif tokens[0] == 'up':
aim -= int(tokens[1])
return {'horizontal': horizontal, 'depth': depth}
# tests
def test_navigation():
test_commands = ['forward 5', 'down 5', 'forward 8', 'up 3', 'down 8', 'forward 2']
position = navigate(test_commands)
assert position['horizontal'] * position['depth'] == 150, 'should be 150'
position = navigate_with_aim(test_commands)
assert position['horizontal'] * position['depth'] == 900, 'should be 90'
def main():
f = open('day2_input.txt', 'r')
commands = f.readlines()
# part 1
position = navigate(commands)
result = position['horizontal'] * position['depth']
print(f'Result for part 1 is {result}')
# part 2
position = navigate_with_aim(commands)
result = position['horizontal'] * position['depth']
print(f'Result for part 2 is {result}')
if __name__ == "__main__":
main()