const std = @import("std"); const print = std.debug.print; const matrixSize = 10; const iterations = std.math.maxInt(u32); // const iterations = 100; // const iterations = 10; const Point = [2]usize; const NeighborList = struct { fn init(alloc: *std.mem.Allocator, x: usize, y: usize) std.ArrayList(Point) { var list = std.ArrayList(Point).init(alloc); for ([_]i8{-1, 0, 1}) |a| { var _x = @intCast(i8, x & 0xf) + a; if (_x < 0 or _x >= matrixSize) continue; for ([_]i8{-1, 0, 1}) |b| { var _y = @intCast(i8, y & 0xf) + b; if (_y < 0 or _y >= matrixSize) continue; if (a == 0 and b == 0) continue; list.append(Point{@intCast(usize, _x), @intCast(usize, _y)}) catch {}; } } return list; } }; pub fn main() !void { var alloc = std.heap.GeneralPurposeAllocator(.{}){}; defer std.debug.assert(!alloc.deinit()); var gpa = &alloc.allocator; const stdin = std.io.getStdIn().reader(); var flashes: u32 = 0; var fullFlashStep: u32 = 0; var matrix: [matrixSize][matrixSize]u8 = undefined; // parse data { var tmp: [256]u8 = undefined; var i: u8 = 0; while (try stdin.readUntilDelimiterOrEof(&tmp, '\n')) |line| { for (line) |char, j| { matrix[i][j] = char - 0x30; } i += 1; } } var i: u32 = 0; while (i < iterations) : (i += 1) { // print("iteration {}\n", .{i}); var flashed: [matrixSize][matrixSize]bool = undefined; for (matrix) |row, x| { for (row) |_, y| { matrix[x][y] += 1; } } while (true) { var retry = false; for (matrix) |row, x| { for (row) |tile, y| { if (matrix[x][y] > 9 and !flashed[x][y]) { flashed[x][y] = true; retry = true; if (i < 100) flashes += 1; var neigh = NeighborList.init(gpa, x, y); defer neigh.deinit(); for (neigh.items) |point| { matrix[point[0]][point[1]] += 1; } } } } if (!retry) break; } var numFlashed: u8 = 0; for (flashed) |row, x| { for (row) |hasFlashed, y| { if (hasFlashed) { matrix[x][y] = 0; numFlashed += 1; } } } if (numFlashed == comptime matrixSize * matrixSize) { fullFlashStep = i + 1; break; } // for (matrix) |row| { // print("{any}\n", .{row}); // } } print("{}\n", .{flashes}); print("{}\n", .{fullFlashStep}); }