adventofcode-2021/day04/part2.lua
2021-12-05 12:17:39 +01:00

65 lines
1.3 KiB
Lua
Executable File

#!/usr/bin/env luajit
require("utils")
local f = io.open(arg[3])
local numbers = split(f:read("*l"), ",")
local line = f:read("*l")
local boards = {}
while line ~= nil do
local board = {}
for r = 1, 5 do
line = f:read("*l")
while line:byte(1) == string.byte(" ", 1) do
line = line:sub(2)
end
board[r] = split(line, " +")
end
table.insert(boards, board)
line = f:read("*l")
end
function finished(board, row, col)
local j, rowints, colints = 1, 0, 0
while j <= 5 and (rowints == 0 or colints == 0) do
if board[row][j] ~= nil then rowints = rowints + 1 end
if board[j][col] ~= nil then colints = colints + 1 end
j = j + 1
end
return rowints == 0 or colints == 0
end
local i = 1
local complete
while #boards > 0 and i <= #numbers do
local number = numbers[i]
local nboards = {}
for b, board in pairs(boards) do
complete = board
local hasfinished = false
for r, row in pairs(board) do
for c, col in pairs(row) do
if col == number then
row[c] = nil
if finished(board, r, c) then
hasfinished = true
end
end
end
end
if not hasfinished then
table.insert(nboards, board)
end
end
boards = nboards
i = i + 1
end
local sum = 0
for r = 1, 5 do
for c = 1, 5 do
sum = sum + (complete[r][c] or 0)
end
end
print(numbers[i - 1] * sum)