2021aoc/Day11.cs

47 lines
1.4 KiB
C#

// #define Day11
#if Day11
using AoC2021;
const int GRID_SIZE = 10;
var grid = File.ReadAllLines("day11/input")
.SelectMany((l,row) =>
l.Select((c, col) => new {pos = new Pos(row, col), v = int.Parse(c.ToString())}))
.ToDictionary(x => x.pos, x => x.v);
long flashes = 0;
int flashesPerStep = 0;
int count = 0;
while (true) {
flashesPerStep = 0;
grid = grid.ToDictionary(x => x.Key, x => x.Value + 1);
grid.Keys.ForEachAsList(p => grid = flash(p, grid));
count++;
if (flashesPerStep == 100) { Console.WriteLine(count); break; }
if (count == 100) { Console.WriteLine(flashes); }
}
Dictionary<Pos, int> flash(Pos cur, Dictionary<Pos, int> grid) {
if (grid[cur] < 10) {
return grid;
}
flashes++;
flashesPerStep++;
grid[cur] = 0;
var adjacent = GetAdjacent(cur);
adjacent.Where(a => grid[a] != 0).ForEachAsList(a => grid[a] += 1);
adjacent.Where(a=> grid[a] > 9).ForEachAsList(a => grid = flash(a, grid));
return grid;
}
List<Pos> GetAdjacent(Pos p) => new List<Pos>() {
new(p.row-1, p.col), new(p.row-1, p.col+1), new(p.row-1, p.col-1),
new(p.row+1, p.col), new(p.row+1, p.col+1), new(p.row+1, p.col-1),
new(p.row, p.col+1), new(p.row, p.col-1),
}.Where(x => x.row >= 0 && x.row < GRID_SIZE && x.col >= 0 && x.col < GRID_SIZE).ToList();
record Pos(int row, int col);
#endif