Photo by Any Lane from Pexels

I’m participating in the Advent of Code 2021. Here’s my solution for Day 2, Puzzle 1 - Dive!

Problem

Puzzle 1 today involves following a series of commands that will take you forward, up or down. Each line of input is a command, followed by a number in the form of :

forward 10

Solution

All my solutions are written in C#. You can find all my solutions in my Git repo.

For this solution, we’ll iterate through the input rows one at a time, splitting the command and value and then incrementing/decrementing the related tracking variable for forward or depth by the appropriate amount. I went ahead and used the if/else pattern, but this could easily have been a switch function as well.

Console.WriteLine("Advent of Code 2021");
Console.WriteLine("Day 2 - Dive");

//Solution logic goes here

//Load input array
string[] lines = System.IO.File.ReadAllLines("input.txt");

int depth = 0, forward = 0;
for (int i = 0; i < lines.Length; i++)
{
    ///parse the command and adjust the appropriate tracking variable
    var cmd = lines[i].Split(' ');
    if (cmd[0] == "forward")
    {
        forward+=int.Parse(cmd[1]);
    }
    else if (cmd[0] == "down")
    {
        depth+=int.Parse(cmd[1]);
    }
    else
    {
        depth -= int.Parse(cmd[1]);
    }
}

//Write out the solution
Console.WriteLine($"Forward: {forward}");
Console.WriteLine($"Depth: {depth}");
Console.WriteLine($"Product: {forward * depth}");

//Stop and wait for enter before exiting
Console.ReadLine();

The answer is 1947824

Part 2

Puzzle 2 today involves reworking the commands from puzzle 1 to instead interpret the up/down to be an aiming value. And when you move forward, it also adjusts depth based on that aim (depth adjusted by forward * current aim).

Solution

All my solutions are written in C#. You can find all my solutions in my Git repo.

This solution is almost identical to puzzle 1 from today. We’ll add an aim variable. When we get an up/down command, we’ll adjust aim instead of depth. And when we get a forward command, we’ll adjust depth by forward*aim.

Console.WriteLine("Advent of Code 2021");
Console.WriteLine("Day 2 - Adding Aim");

//Solution logic goes here

//Load input array
string[] lines = System.IO.File.ReadAllLines("input.txt");

int depth = 0, forward = 0, aim=0;
for (int i = 0; i < lines.Length; i++)
{
    ///parse the command and adjust the appropriate tracking variable
    var cmd = lines[i].Split(' ');
    if (cmd[0] == "forward")
    {
        var x= int.Parse(cmd[1]);
        forward += x;
        depth += x * aim;
    }
    else if (cmd[0] == "down")
    {
        aim += int.Parse(cmd[1]);
    }
    else
    {
        aim -= int.Parse(cmd[1]);
    }
}

//Write out the solution
Console.WriteLine($"Forward: {forward}");
Console.WriteLine($"Depth: {depth}");
Console.WriteLine($"Product: {forward * depth}");

//Stop and wait for enter before exiting
Console.ReadLine();

The answer is 1813062561