AoC 2021 - Day 2
Day 2 of Advent of Code is here, and it turned out to be pretty easy. Starting off all we get is a list of instructions of the form <instruction> <parameter>
where <instruction>
is one of forward
, up
or down
and <parameter>
is an integer.
My idea to parse this list of instructions was to create a list of tuples of the form (instruction, parameter)
using a regular expression ^([a-z]+) ([0-9]+)$
. This regular expression makes use of capturing groups to extract the instruction and the parameter separately. The groups are accessed using match.group(1)
and match.group(2)
.
Task 1
Here my idea was to use a dictionary to store functions (lambdas) under keys 'forward'
, 'up'
and 'down'
. The functions are then called with the parameter as argument together with the current position.
I used functools.reduce
to fold the list of instructions into a single final position. Reduce represents in Python the mathematical concept of a fold, which also is a commonly used operation in functional programming. The function functools.reduce
takes a function, a list and an initial value as arguments. The function is applied to the initial value and the first element of the list, then the result is used as the initial value for the next iteration. The result of the last iteration is returned.
This operation can be represented as foldl f z xs
in some other functional languages:
Here’s my solution:
The key part is right here:
Task 2
Task 2 was pretty much identical to task 1. I used a dictionary to store functions (lambdas) under keys 'forward'
, 'up'
and 'down'
, except that the functions have different bodies and they take an additional parameter a
for aim.