Skip to content

Commit

Permalink
2024 Day 6 (brute force)
Browse files Browse the repository at this point in the history
  • Loading branch information
premun committed Dec 6, 2024
1 parent 488f230 commit 23bd72b
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 3 deletions.
76 changes: 73 additions & 3 deletions src/2024/06/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,76 @@
using AdventOfCode.Common;
using Coor = AdventOfCode.Common.Coor<int>;

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

Console.WriteLine($"Part 1: {""}");
Console.WriteLine($"Part 2: {""}");
var directions = new Dictionary<char, Coor>
{
{ '^', Coor.Up },
{ '>', Coor.Right },
{ 'V', Coor.Down },
{ '<', Coor.Left },
};

Simulate(map);
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);
}
catch (LoopException)
{
possibleObstaclePositions++;
}
}

Console.WriteLine($"Part 1: {traversedPath.Count}");
Console.WriteLine($"Part 2: {possibleObstaclePositions}");

static void Simulate(char[,] map)
{
var position = map.AllCoordinates().First(c => map.Get(c) == '^');
var direction = Coor.Up;
map.Set(position, (char)0);

while (true)
{
var current = map.Get(position);
map.Set(position, (char)(current switch
{
'.' => 1,
_ => 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;
9 changes: 9 additions & 0 deletions src/Common/Coor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,4 +101,13 @@ public static void Visualize(this ICollection<Coor<int>> coors, Coor<int>? min,
Console.WriteLine();
}
}

public static Coor<T> TurnRight<T>(this Coor<T> direction) where T : INumber<T> => direction switch
{
_ when direction == Coor<T>.Up => Coor<T>.Right,
_ when direction == Coor<T>.Right => Coor<T>.Down,
_ when direction == Coor<T>.Down => Coor<T>.Left,
_ when direction == Coor<T>.Left => Coor<T>.Up,
_ => throw new NotImplementedException()
};
}

0 comments on commit 23bd72b

Please sign in to comment.