Dive
This problem doesn’t lend itself very well to a one-line description, but basically:
- Compute some simple values (e.g. sums) from a sequence of text lines of the form
<command> <int>
.
Both part 1 and part 2 are like this, I don’t really see a difference.
The simplest approach, I think, is to either do cmd, n = line.split(' ', 1)
over the lines, or to use a regular expression to iterate over matches directly.
I went for the latter because it’s more flexible, and probably just in general a
better approach for this kind of problem when dealing with
Python.
import re
inp = __import__('aoc-common').aoc().input_text(2)
expr = re.compile(r"^(?P<dir>forward|down|up) (?P<n>\d+)$", re.M)
h, d = 0, 0
for m in expr.finditer(inp):
n = int(m['n'])
if m['dir'] == 'forward':
h += n
else:
d += -n if m['dir'] == 'up' else n
print(f'answer for part 1: {h*d}')
aim, h, d = 0, 0, 0
for m in expr.finditer(inp):
n = int(m['n'])
if m['dir'] == 'forward':
h += n
d += aim * n
else:
aim += -n if m['dir'] == 'up' else n
print(f'answer for part 2: {h*d}')