about summary refs log tree commit diff
path: root/aoc2021/Day02.cs
blob: a09952025dff912fc6b1dc513df85a46b4d3ab29 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
namespace aoc2021;

/// <summary>
/// Day 2: <see href="https://adventofcode.com/2021/day/2"/>
/// </summary>
public sealed class Day02 : Day
{
    public Day02() : base(2, "Dive!")
    {
    }

    public override string Part1()
    {
        int horiz = 0, depth = 0;
        foreach (var line in Input)
        {
            var s = line.Split(' ');
            var x = int.Parse(s[1]);
            switch (s[0])
            {
                case "forward":
                    horiz += x;
                    break;
                case "down":
                    depth += x;
                    break;
                case "up":
                    depth -= x;
                    break;
            }
        }

        return $"{horiz * depth}";
    }

    public override string Part2()
    {
        int aim = 0, depth = 0, horiz = 0;
        foreach (var line in Input)
        {
            var s = line.Split(' ');
            var x = int.Parse(s[1]);
            switch (s[0])
            {
                case "forward":
                    horiz += x;
                    depth += aim * x;
                    break;
                case "down":
                    aim += x;
                    break;
                case "up":
                    aim -= x;
                    break;
            }
        }

        return $"{horiz * depth}";
    }
}