Pages

2021/12/03

Advent of Code 2021 - Day 2

This is a running series of posts on the Advent of Code 2020. The introductory post has the details, including the accompanying GitHub repo, in case you reached this directly.

Today we process some directions consisting of a command and an argument. We start at (0, 0) in a two-dimensional space, and there are commands of the form direction argument, where direction can be forward, up or down, and the argument is a positive integer. The exact interpretation changes in each part.

Part 1

The interpretation of the commands is straightforward in this part: forward increases x, up decreases y, and down increases y; up and down seem to be inverted, but the story is about a submarine and the y axis represents depth, so it makes sense, and the description reminds us often of this. The argument is the step taken in the given direction.

Rather than updating after each step, we can take advantage of the associative property of addition to just add together the arguments for each direction and then calculate the movement horizontally (forward)  and vertically (down - up). We use a defaultdict as accumulator for easier reading; otherwise we would need to use a normal dictionary with the three values initialized as 0.

Part 2

For this part there is a third concept: aim, a sort of heading. up and down now change the heading, and forward moves horizontally by its argument as before, but also vertically by aim times the argument. This forces to track the state step by step, but it's just a matter of having three variables (two for the position, one for the aim) and applying each command with a plain if-elif-else structure.

No comments:

Post a Comment