diff --git a/AdventOfCode/Day21.cs b/AdventOfCode/Day21.cs index 710179d..d6fd0f6 100644 --- a/AdventOfCode/Day21.cs +++ b/AdventOfCode/Day21.cs @@ -6,16 +6,21 @@ public class Day21 : BaseDay public Day21() { - _codes = File.ReadAllLines(InputFilePath); + _codes = ["029A", "980A", "179A", "456A", "379A"]; //File.ReadAllLines(InputFilePath); } public override ValueTask Solve_1() { - List paths = GetAllPaths("029A"); - - int shortestLength = paths.Min(p => p.Length); + int res = 0; + foreach (var code in _codes) + { + int length = GetShortestPath(code); + int num = int.Parse(code.Replace("A", "")); + Console.WriteLine($"{length} * {num}"); + res += length * num; + } - return new((shortestLength * 29).ToString()); + return new(res.ToString()); } public override ValueTask Solve_2() @@ -23,7 +28,7 @@ public override ValueTask Solve_2() return new(""); } - private List GetAllPaths(string code) + private int GetShortestPath(string code) { List one = GetAllPaths(code, _numpad, new Dictionary<(Position, Position), List>()); @@ -36,14 +41,17 @@ private List GetAllPaths(string code) two.AddRange(GetAllPaths(path, _directionalPad, cache)); } - List three = new List(); + int shortest = int.MaxValue; foreach (string path in two) { - //var t = GetAllPaths(path, _directionalPad, cache); - //three.AddRange(t); + var t = GetPathLength(path, _directionalPad, cache); + if (t < shortest) + { + shortest = t; + } } - return three; + return shortest; } private List GetAllPaths( @@ -79,6 +87,38 @@ private List GetAllPaths( return paths; } + private int GetPathLength( + string code, + Dictionary pad, + Dictionary<(Position, Position), List> cache + ) + { + Position from = pad['A']; + int length = 0; + + foreach (char button in code) + { + Position to = pad[button]; + + if (cache.ContainsKey((from, to))) + { + length += cache[(from, to)][0].Length; + length++; + } + else + { + var segments = GetAllPaths(from, to, "", cache); + cache[(from, to)] = segments; + length += cache[(from, to)][0].Length; + length++; + } + + from = to; + } + + return length; + } + private List GetAllPaths( Position from, Position to,