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 antennas = new Dictionary<char, List<Position>>();
- for (var row = 0; row < gridSize; row++)
- {
- for (var col = 0; col < gridSize; col++)
- {
- var cell = input[row][col];
- if (cell != '.')
- {
- if (!antennas.TryGetValue(cell, out _))
- {
- antennas[cell] = [];
- }
- antennas[cell].Add(new Position(row, col));
- }
- }
- }
- var antinodes1 = new HashSet<Position>();
- var antinodes2 = new HashSet<Position>();
- foreach (var frequency in antennas.Keys)
- {
- var locations = antennas[frequency];
- foreach (var a in locations)
- {
- foreach (var b in locations)
- {
- if (a == b)
- {
- continue;
- }
- var rowDiff = a.Row - b.Row;
- var colDiff = a.Col - b.Col;
- var antinodeA = a.Move(rowDiff, colDiff);
- if (!antinodeA.OutOfBounds(gridSize))
- {
- antinodes1.Add(antinodeA);
- }
- while (!antinodeA.OutOfBounds(gridSize))
- {
- antinodes2.Add(antinodeA);
- antinodeA = antinodeA.Move(rowDiff, colDiff);
- }
- var antinodeB = b.Move(-rowDiff, -colDiff);
- if (!antinodeB.OutOfBounds(gridSize))
- {
- antinodes1.Add(antinodeB);
- }
- while (!antinodeB.OutOfBounds(gridSize))
- {
- antinodes2.Add(antinodeB);
- antinodeB = antinodeB.Move(-rowDiff, -colDiff);
- }
- antinodes2.Add(a);
- antinodes2.Add(b);
- }
- }
- }
- Console.WriteLine($"Part 1: {antinodes1.Count}");
- Console.WriteLine($"Part 2: {antinodes2.Count}");
- internal record Position(int Row, int 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