Module advent_of_code_2021::day_2 [−][src]
Expand description
This is my solution for Advent of Code - Day 2 - Dive!
Today involves parsing a sequence of instructions that direct the submarine to move on a grid.
First parse_line is used to parse the string input into an internal representation
Instruction. Rust has powerful pattern matching but requires that it is exhaustive. Front
loading parsing the strings both makes the code more understandable, but also simplifies the
match statements as we don’t need to repeatedly handle possible bad input.
The two parts differ in how the input should be interpreted. I’ve implemented both as a fold
over the sequence of instructions, matching the Direction and updating the position as specified
for that part. Part one takes the instructions at face value, the logic is implemented by
navigate. Part two tracks a third variable ‘aim’, but is otherwise very similar. The logic
is implemented by navigate_and_aim.
Enums
There are three direction strings expected in the input. Parsing those into an Enum type helps doing exhaustive matches later
Functions
This starts with the submarine at the origin, and moves using the following rules:
This starts with the submarine at the origin, with a third variable ‘aim’ also set to 0. The position and aim are updated using the following rules:
Parses a line in the format (forward|up|down) \d+ into the internal representation
Instruction. Will panic if the provided line does not match the expected format.
The entry point for running the solutions with the ‘real’ puzzle input.
Type Definitions
Each line of the input is a pair of direction and magnitude - alias this for clarity
