Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var input = await File.ReadAllLinesAsync("input.txt");
- var gridSize = input.Length;
- var coordinatesX = new List<Position>();
- var coordinatesA = new List<Position>();
- for (var row = 0; row < gridSize; row++)
- {
- for (var col = 0; col < gridSize; col++)
- {
- switch (input[row][col])
- {
- case 'X':
- coordinatesX.Add(new Position(row, col));
- break;
- case 'A':
- coordinatesA.Add(new Position(row, col));
- break;
- }
- }
- }
- var part1 = coordinatesX.Sum(CheckPositionX);
- var part2 = coordinatesA.Count(CheckPositionA);
- Console.WriteLine($"Part 1: {part1}");
- Console.WriteLine($"Part 2: {part2}");
- return;
- int CheckPositionX(Position x)
- {
- var result = 0;
- for (var row = -1; row <= 1; row++)
- {
- for (var col = -1; col <= 1; col++)
- {
- if (row == 0 && col == 0)
- {
- continue;
- }
- var m = x.Move(row, col);
- var a = m.Move(row, col);
- var s = a.Move(row, col);
- if (m.OutOfBounds(gridSize) ||
- a.OutOfBounds(gridSize) ||
- s.OutOfBounds(gridSize))
- {
- continue;
- }
- if (input[m.Row][m.Col] == 'M' &&
- input[a.Row][a.Col] == 'A' &&
- input[s.Row][s.Col] == 'S')
- {
- result++;
- }
- }
- }
- return result;
- }
- bool CheckPositionA(Position a)
- {
- if (a.OutOfBounds(1, gridSize - 1))
- {
- return false;
- }
- var topLeft = input[a.Row - 1][a.Col - 1];
- var topRight = input[a.Row - 1][a.Col + 1];
- var bottomLeft = input[a.Row + 1][a.Col - 1];
- var bottomRight = input[a.Row + 1][a.Col + 1];
- return topLeft == 'M' && topRight == 'M' && bottomLeft == 'S' && bottomRight == 'S'
- || topLeft == 'M' && topRight == 'S' && bottomLeft == 'M' && bottomRight == 'S'
- || topLeft == 'S' && topRight == 'S' && bottomLeft == 'M' && bottomRight == 'M'
- || topLeft == 'S' && topRight == 'M' && bottomLeft == 'S' && bottomRight == 'M';
- }
- internal class Position(int row, int col)
- {
- public readonly int Row = row;
- public readonly int Col = col;
- public Position Move(int row, int col)
- {
- return new Position(Row + row, Col + col);
- }
- public bool OutOfBounds(int size)
- {
- return OutOfBounds(0, size);
- }
- public bool OutOfBounds(int start, int end)
- {
- return Row < start || Row >= end || Col < start || Col >= end;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement