-
Notifications
You must be signed in to change notification settings - Fork 1
/
Program.cs
66 lines (55 loc) · 1.56 KB
/
Program.cs
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
61
62
63
64
65
66
using AdventOfCode.Common;
using Coor = AdventOfCode.Common.Coor<int>;
char[,] map = Resources.GetInputFileLines().ParseAsArray();
Coor start = map.AllCoordinates().First(c => map.Get(c) == '^');
Simulate(map, start);
var traversedPath = map.AllCoordinates()
.Where(c => map.Get(c) != '.' && map.Get(c) != '#')
.ToList();
var possibleObstaclePositions = 0;
foreach (var path in traversedPath.Where(c => c != start))
{
try
{
var newMap = Resources.GetInputFileLines().ParseAsArray();
newMap.Set(path, '#');
Simulate(newMap, start);
}
catch (LoopException)
{
possibleObstaclePositions++;
}
}
Console.WriteLine($"Part 1: {traversedPath.Count}");
Console.WriteLine($"Part 2: {possibleObstaclePositions}");
static void Simulate(char[,] map, Coor position)
{
var direction = Coor.Up;
while (true)
{
var current = map.Get(position);
map.Set(position, current switch
{
'.' => '0',
_ => (char)(current + 1),
});
var next = position + direction;
if (!next.InBoundsOf(map))
{
break;
}
if (map.Get(next) == '#')
{
direction = direction.TurnRight();
continue;
}
// We can only come to a field twice (from side and from top/down)
// If we come a third time, it's a loop
if (map.Get(next) != '.' && map.Get(next) == '3')
{
throw new LoopException();
}
position = next;
}
}
file class LoopException : Exception;