-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday2_dive.py
74 lines (42 loc) · 1.11 KB
/
day2_dive.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
#!/usr/bin/env python
# coding: utf-8
import re
from collections import defaultdict
filename = 'day2_dive.txt'
with open(filename, 'r') as infile:
commands = infile.readlines()
# # Part 1
parsed = [re.match(r'(\w+) (\d+).*', cmd).groups() for cmd in commands]
totals = defaultdict(int)
for cmd, val in parsed:
totals[cmd] += int(val)
totals
fwd = totals['forward']
depth = totals['down'] - totals['up']
print(fwd)
print(depth)
fwd*depth
# # Part 2
class State:
def __init__(self):
self.fwd = 0
self.depth = 0
self.aim = 0
def run_cmd(self, command, val):
if command == 'up':
#self.depth -= val
self.aim -= val
elif command == 'down':
#self.depth += val
self.aim += val
elif command == 'forward':
self.fwd += val
self.depth += val*self.aim
def __str__(self):
return f'fwd = {self.fwd}, depth = {self.depth}, aim = {self.aim}'
s = State()
for cmd, val in parsed:
s.run_cmd(cmd, int(val))
print(cmd, val)
print(s)
s.fwd * s.depth