about summary refs log tree commit diff
path: root/Day3.cs
blob: 442c58aa024292fb313dda1d05f785ead5849e42 (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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace aoc2019
{
    internal class Day3 : Day
    {
        public override int DayNumber => 3;

        private readonly IEnumerable<(int, int)> intersections;
        private readonly List<Dictionary<(int, int), int>> wires;

        public Day3()
        {
            wires = Input.Select(ParseWire).ToList();
            intersections = wires[0].Keys.Intersect(wires[1].Keys);
        }

        public override string Part1()
        {
            return $"{intersections.Min(x => Math.Abs(x.Item1) + Math.Abs(x.Item2))}";
        }

        public override string Part2()
        {
            // add 2 to count (0, 0) on both lines
            return $"{intersections.Min(x => wires[0][x] + wires[1][x]) + 2}";
        }

        private static Dictionary<(int, int), int> ParseWire(string line)
        {
            var r = new Dictionary<(int, int), int>();
            int x = 0, y = 0, c = 0, i;

            foreach (var step in line.Split(','))
            {
                var d = int.Parse(step.Substring(1));
                switch (step[0])
                {
                    case 'U': for (i = 0; i < d; i++) r.TryAdd((x, ++y), c++); break;
                    case 'D': for (i = 0; i < d; i++) r.TryAdd((x, --y), c++); break;
                    case 'R': for (i = 0; i < d; i++) r.TryAdd((++x, y), c++); break;
                    case 'L': for (i = 0; i < d; i++) r.TryAdd((--x, y), c++); break;
                }
            }

            return r;
        }
    }
}