How to solve Advent of Code 2021 – Day 2 [Python]

Advent Of Code with Day(2)
Advent Of Code with Day(2)

Confused? Check out my Day 1 post to read all about Advent of Code here: https://galaxyinferno.com/how-to-solve-advent-of-code-2021-day-1/

GitHub

https://github.com/GalaxyInfernoCodes/Advent_Of_Code_2021

This is where I will upload all of my Python Notebooks where I solve the challenges. I’m solving them on Google Colab, because that allows me to just quickly throw something together in the Browser on any machine I’m on. Since I’m lazy, that’s my go-to for quick and small projects. Otherwise I code in VSCode 🙂

Day 2 Puzzle

Here is the challenge, if you want to read the full puzzle: https://adventofcode.com/2021/day/2

Part 1

The input this time looked like this:

forward 5
down 5
forward 8
up 3
down 8
forward 2

You were supposed to keep track of the horizontal position and depth, where forward adds values to the horizontal position, up decreases the depth value and down increases the depth value – as you would imagine.

So the only tricky part here was to read the input, then split the string and convert the last part into an integer so you could add the value. Oh, and I guess you needed to check which of the three possible commands were used in the string.

I read in the input as in the previous day:

with open('input.txt', 'r') as f:
    lines = f.readlines()
    commands = [entry.strip() for entry in lines]

And then split the string and added the appropriate values together:

horizontal_pos, depth = 0, 0

for command in commands:
    direction, amount = command.split(' ')[0], int(command.split(' ')[1])
    if 'forward' in direction:
        horizontal_pos += amount
    elif 'up' in direction:
        depth -= amount
    elif 'down' in direction:
        depth += amount

Part 2

Here they told us that ”we” in the story understood something wrong?! Anyways, instead we should also track the aim and the commands now do something slightly different, but that only meant that we had to slightly alter what the commands do:

horizontal_pos, depth, aim = 0, 0, 0

for command in commands:
    direction, amount = command.split(' ')[0], int(command.split(' ')[1])
    if 'forward' in direction:
        horizontal_pos += amount
        depth += aim * amount
    elif 'up' in direction:
        aim -= amount
    elif 'down' in direction:
        aim += amount

Conclusion

Day 2 was still very simple, solvable with a for loop and some if statements. The only thing added here was the splitting of strings to use 2 components, but (SPOILER) I struggled a bit longer with Day 3, so stay tuned for that 😉

Leave a Reply