Right, on to the next part, Day 2 of Advent of Code.
This time, we're trying to work out where our submarine is going. Our input is a series of instructions, like this:
forward 5
down 5
forward 8
up 3
down 8
forward 2
We need to calculate the final horizontal and vertical position, and multiply the values to get our answer for Part 1. Bear in mind that by going down, we're actually increasing our depth, meaning that we're increasing the horizontal position.
To make this solution a little more readable, I decided to create a small class defining the instructions.
internal class Instruction
{
public Instruction(string input)
{
var temp = input.Split(" ");
Direction = temp[0];
Distance = int.Parse(temp[1]);
}
public string Direction { get; set; }
public int Distance { get; set; }
}
Then, as always, we parse the input:
var input = (await File.ReadAllLinesAsync("input.txt")).Select(x => new Instruction(x)).ToArray();
From there, it's quite simple. Just go through the instructions and calculate the horizontal position and the depth accordingly, and multiply them by the end.
private static void Part1(IEnumerable<Instruction> input)
{
var depth = 0;
var horizontal = 0;
foreach (var instruction in input)
{
switch (instruction.Direction)
{
case "forward":
horizontal += instruction.Distance;
break;
case "down":
depth += instruction.Distance;
break;
case "up":
depth -= instruction.Distance;
break;
}
}
Console.WriteLine($"Answer Part1: {depth * horizontal}");
}
Part 2 makes it a little bit more complicated, but not that much. It turns out that there is a third parameter, "aim". It seems that up and down is related to aim, not depth. Depth is actually calculated by using aim and horizontal position. The solution is very similar, loop through the instructions and calculate our parameters according to the requirements. The answer is still the product of multiplying depth and horizontal position.
private static void Part2(IEnumerable<Instruction> input)
{
var depth = 0;
var horizontal = 0;
var aim = 0;
foreach (var instruction in input)
{
switch (instruction.Direction)
{
case "forward":
horizontal += instruction.Distance;
depth += (aim * instruction.Distance);
break;
case "down":
aim += instruction.Distance;
break;
case "up":
aim -= instruction.Distance;
break;
}
}
Console.WriteLine($"Answer Part2: {depth * horizontal}");
}
That's it for day 2.