adventofcode-2021/day11/part2.lua

61 lines
1.0 KiB
Lua
Raw Permalink Normal View History

2021-12-11 10:05:05 +01:00
#!/usr/bin/env luajit
require("utils")
local grid = {}
for line in io.lines(arg[3]) do
local row = {}
for char in chars(line) do
table.insert(row, tonumber(char))
end
table.insert(grid, row)
end
function printgrid()
for r, row in pairs(grid) do
for c, cell in pairs(row) do
if cell > 9 then
io.write('*')
else
io.write(cell)
end
end
io.write('\n')
end
end
printgrid()
function flash(grid, r, c)
grid[r][c] = grid[r][c] + 1
if grid[r][c] == 10 then
for dr = -1, 1 do if 0 < r + dr and r + dr <= #grid then
for dc = -1, 1 do if 0 < c + dc and c + dc <= #grid[r] then
flash(grid, r + dr, c + dc)
end end
end end
end
end
for step = 1, math.huge do
for r, row in pairs(grid) do
for c, cell in pairs(row) do
flash(grid, r, c)
end
end
local flashes = 0
for r, row in pairs(grid) do
for c, cell in pairs(row) do
if cell > 9 then
grid[r][c] = 0
flashes = flashes + 1
end
end
end
print(flashes)
printgrid()
if flashes == #grid * #grid[1] then
print(step)
break
end
end