Skip to content

Commit

Permalink
day 15 part 1
Browse files Browse the repository at this point in the history
  • Loading branch information
KaterynaKateryna committed Dec 15, 2024
1 parent 60113de commit c1977d3
Showing 1 changed file with 120 additions and 0 deletions.
120 changes: 120 additions & 0 deletions AdventOfCode/Day15.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@

namespace AdventOfCode;

public class Day15 : BaseDay
{
private readonly char[][] _map;
private readonly List<char> _moves = new List<char>();
private Position _robot;

public Day15()

Check warning on line 10 in AdventOfCode/Day15.cs

View workflow job for this annotation

GitHub Actions / build-and-run

Non-nullable field '_robot' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the field as nullable.

Check warning on line 10 in AdventOfCode/Day15.cs

View workflow job for this annotation

GitHub Actions / build-and-run

Non-nullable field '_robot' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the field as nullable.
{
string[] lines = File.ReadAllLines(InputFilePath);

int width = lines[0].Length;
int height = lines.Count(l => l.StartsWith("#"));

_map = new char[height][];
for (int i = 0; i < height; ++i)
{
_map[i] = lines[i].ToCharArray();

int j = lines[i].IndexOf('@');
if (j >= 0)
{
_robot = new Position(i, j);
}
}

foreach (var line in lines.Skip(height + 1))
{
_moves.AddRange(line.ToList());
}
}

public override ValueTask<string> Solve_1()
{
foreach (char move in _moves)
{
Move(move);
}

int gps = GetGPS();

return new(gps.ToString());
}

public override ValueTask<string> Solve_2()
{
return new("");
}

private void Move(char move)
{
Position next = GetNext(move, _robot);

Position firstNext = next;
bool movesBoxes = false;

while (true)
{
char nextChar = _map[next.I][next.J];
if (nextChar == '#')
{
return; // wall = do nothing
}
if (nextChar == '.')
{
if (movesBoxes)
{
_map[next.I][next.J] = 'O';
}
_map[firstNext.I][firstNext.J] = '@';
_map[_robot.I][_robot.J] = '.';
_robot = firstNext;
return;
}
if (nextChar == 'O')
{
next = GetNext(move, next);
movesBoxes = true;
}
}
}

private Position GetNext(char move, Position from)
{
switch (move)
{
case '^':
return new Position(from.I - 1, from.J);
case 'v':
return new Position(from.I + 1, from.J);
case '>':
return new Position(from.I, from.J + 1);
case '<':
return new Position(from.I, from.J - 1);
default:
throw new NotImplementedException();
}
}

private int GetGPS()
{
int result = 0;
for (int i = 0; i < _map.Length; ++i)
{
for (int j = 0; j < _map[i].Length; ++j)
{
if (_map[i][j] == 'O')
{
result += 100 * i + j;
}
}
}

return result;
}

private record Position(int I, int J);
}

0 comments on commit c1977d3

Please sign in to comment.