about summary refs log tree commit diff
path: root/Day03.cs
diff options
context:
space:
mode:
authorBen Harris <ben@tilde.team>2020-12-16 17:17:35 -0500
committerBen Harris <ben@tilde.team>2020-12-16 17:17:35 -0500
commit837527d487c7e232b36dd87c95a15b7852f2e057 (patch)
tree21ddf9a63548ccc8c802fe5f158f3e6743a8e9f1 /Day03.cs
parentc66d1d6b335e6c2f6b544ae31793f318ba2b99a7 (diff)
refactor to two-digit day names and add puzzlename
Diffstat (limited to 'Day03.cs')
-rw-r--r--Day03.cs57
1 files changed, 57 insertions, 0 deletions
diff --git a/Day03.cs b/Day03.cs
new file mode 100644
index 0000000..e339c27
--- /dev/null
+++ b/Day03.cs
@@ -0,0 +1,57 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace aoc2019
+{
+    internal sealed class Day03 : Day
+    {
+        private readonly IEnumerable<(int, int)> intersections;
+        private readonly List<Dictionary<(int, int), int>> wires;
+
+        public Day03() : base(3, "Crossed Wires")
+        {
+            wires = Input.Select(ParseWire).ToList();
+            intersections = wires[0].Keys.Intersect(wires[1].Keys);
+        }
+
+        protected override string Part1()
+        {
+            return $"{intersections.Min(x => Math.Abs(x.Item1) + Math.Abs(x.Item2))}";
+        }
+
+        protected 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;
+        }
+    }
+}
\ No newline at end of file