Skip to content

Commit 23bd72b

Browse files
committed
2024 Day 6 (brute force)
1 parent 488f230 commit 23bd72b

File tree

2 files changed

+82
-3
lines changed

2 files changed

+82
-3
lines changed

src/2024/06/Program.cs

+73-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,76 @@
11
using AdventOfCode.Common;
2+
using Coor = AdventOfCode.Common.Coor<int>;
23

3-
var lines = Resources.GetInputFileLines();
4+
char[,] map = Resources.GetInputFileLines().ParseAsArray();
5+
Coor start = map.AllCoordinates().First(c => map.Get(c) == '^');
46

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;

src/Common/Coor.cs

+9
Original file line numberDiff line numberDiff line change
@@ -101,4 +101,13 @@ public static void Visualize(this ICollection<Coor<int>> coors, Coor<int>? min,
101101
Console.WriteLine();
102102
}
103103
}
104+
105+
public static Coor<T> TurnRight<T>(this Coor<T> direction) where T : INumber<T> => direction switch
106+
{
107+
_ when direction == Coor<T>.Up => Coor<T>.Right,
108+
_ when direction == Coor<T>.Right => Coor<T>.Down,
109+
_ when direction == Coor<T>.Down => Coor<T>.Left,
110+
_ when direction == Coor<T>.Left => Coor<T>.Up,
111+
_ => throw new NotImplementedException()
112+
};
104113
}

0 commit comments

Comments
 (0)