|
1 | 1 | using AdventOfCode.Common;
|
| 2 | +using Coor = AdventOfCode.Common.Coor<int>; |
2 | 3 |
|
3 |
| -var lines = Resources.GetInputFileLines(); |
| 4 | +char[,] map = Resources.GetInputFileLines().ParseAsArray(); |
| 5 | +Coor start = map.AllCoordinates().First(c => map.Get(c) == '^'); |
4 | 6 |
|
5 |
| -Console.WriteLine($"Part 1: {""}"); |
6 |
| -Console.WriteLine($"Part 2: {""}"); |
| 7 | +var directions = new Dictionary<char, Coor> |
| 8 | +{ |
| 9 | + { '^', Coor.Up }, |
| 10 | + { '>', Coor.Right }, |
| 11 | + { 'V', Coor.Down }, |
| 12 | + { '<', Coor.Left }, |
| 13 | +}; |
| 14 | + |
| 15 | +Simulate(map); |
| 16 | +var traversedPath = map.AllCoordinates() |
| 17 | + .Where(c => map.Get(c) != '.' && map.Get(c) != '#') |
| 18 | + .ToList(); |
| 19 | + |
| 20 | +var possibleObstaclePositions = 0; |
| 21 | +foreach (var path in traversedPath.Where(c => c != start)) |
| 22 | +{ |
| 23 | + try |
| 24 | + { |
| 25 | + var newMap = Resources.GetInputFileLines().ParseAsArray(); |
| 26 | + newMap.Set(path, '#'); |
| 27 | + Simulate(newMap); |
| 28 | + } |
| 29 | + catch (LoopException) |
| 30 | + { |
| 31 | + possibleObstaclePositions++; |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +Console.WriteLine($"Part 1: {traversedPath.Count}"); |
| 36 | +Console.WriteLine($"Part 2: {possibleObstaclePositions}"); |
| 37 | + |
| 38 | +static void Simulate(char[,] map) |
| 39 | +{ |
| 40 | + var position = map.AllCoordinates().First(c => map.Get(c) == '^'); |
| 41 | + var direction = Coor.Up; |
| 42 | + map.Set(position, (char)0); |
| 43 | + |
| 44 | + while (true) |
| 45 | + { |
| 46 | + var current = map.Get(position); |
| 47 | + map.Set(position, (char)(current switch |
| 48 | + { |
| 49 | + '.' => 1, |
| 50 | + _ => current + 1, |
| 51 | + })); |
| 52 | + |
| 53 | + var next = position + direction; |
| 54 | + if (!next.InBoundsOf(map)) |
| 55 | + { |
| 56 | + break; |
| 57 | + } |
| 58 | + |
| 59 | + if (map.Get(next) == '#') |
| 60 | + { |
| 61 | + direction = direction.TurnRight(); |
| 62 | + continue; |
| 63 | + } |
| 64 | + |
| 65 | + // We can only come to a field twice (from side and from top/down) |
| 66 | + // If we come a third time, it's a loop |
| 67 | + if (map.Get(next) != '.' && map.Get(next) > 3) |
| 68 | + { |
| 69 | + throw new LoopException(); |
| 70 | + } |
| 71 | + |
| 72 | + position = next; |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +file class LoopException : Exception; |
0 commit comments