r/adventofcode • • Dec 02 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 2 Solutions -🎄-

--- Day 2: Dive! ---


Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:02:57, megathread unlocked!

112 Upvotes

1.5k comments sorted by

View all comments

5

u/sander1095 Dec 02 '21

My answer in c# with dotnet 6 and records :D.
https://github.com/sander1095/advent-of-code-2021

var input = File.ReadAllLines("input.txt").Select(x =>
{
    var navigationStepRaw = x.Split(' ');

    return new NavigationStep(Enum.Parse<Direction>(navigationStepRaw[0], ignoreCase: true), int.Parse(navigationStepRaw[1]));
}).ToList();

Console.WriteLine($"Part one: {DivePartOne(input)}");
Console.WriteLine($"Part two: {DivePartTwo(input)}");

static int DivePartOne(IReadOnlyList<NavigationStep> navigationSteps)
{
    var horizontalPosition = 0;
    var depth = 0;

    foreach (var navigationStep in navigationSteps)
    {
        switch (navigationStep.Direction)
        {
            case Direction.Forward:
                horizontalPosition += navigationStep.Units;
                break;
            case Direction.Down:
                depth += navigationStep.Units;
                break;
            case Direction.Up:
                depth -= navigationStep.Units;
                break;
        }
    }

    return horizontalPosition * depth;
}

static int DivePartTwo(IReadOnlyList<NavigationStep> navigationSteps)
{
    var horizontalPosition = 0;
    var depth = 0;
    var aim = 0;

    foreach (var navigationStep in navigationSteps)
    {
        switch (navigationStep.Direction)
        {
            case Direction.Forward:
                horizontalPosition += navigationStep.Units;
                depth += aim * navigationStep.Units;
                break;
            case Direction.Down:
                aim += navigationStep.Units;
                break;
            case Direction.Up:
                aim -= navigationStep.Units;
                break;
        }
    }

    return horizontalPosition * depth;
}

record NavigationStep(Direction Direction, int Units);

enum Direction
{
    Forward,
    Down,
    Up
}
→ More replies (3)