adventofcode-2021/day09/part2.lua

72 lines
1.5 KiB
Lua
Executable File

#!/usr/bin/env luajit
require("utils")
local hm = {}
for line in io.lines(arg[3]) do
local row = {}
for c in chars(line) do
table.insert(row, tonumber(c))
end
table.insert(hm, row)
end
local function get(r, c)
return (hm[r] or {})[c] or 9
end
local union = {}
for r, row in pairs(hm) do
for c, col in pairs(row) do
if col ~= 9 then
if get(r - 1, c) ~= 9 then
if union[r] == nil then union[r] = {} end
union[r][c] = { r - 1, c }
end
if get(r, c - 1) ~= 9 then
if union[r] == nil then union[r] = {} end
if union[r][c] ~= nil then
local r0, c0 = r, c - 1
while type(union[r0][c0]) == "table" do
r0, c0 = unpack(union[r0][c0])
if union[r0] == nil then union[r0] = {} end
end
local r1, c1 = r, c
while type(union[r1][c1]) == "table" do
r1, c1 = unpack(union[r1][c1])
if union[r1] == nil then union[r1] = {} end
end
if r0 ~= r1 or c0 ~= c1 then
union[r1][c1] = { r0, c0 }
end
else
union[r][c] = { r, c - 1 }
end
end
end
end
end
local sums = {}
for r, row in pairs(hm) do
for c, col in pairs(row) do
if col ~= 9 then
local r0, c0 = r, c
while type(union[r0][c0]) == "table" do
r0, c0 = unpack(union[r0][c0])
end
if sums[r0] == nil then sums[r0] = {} end
sums[r0][c0] = (sums[r0][c0] or 0) + 1
end
end
end
local sizes = {}
for r, row in pairs(sums) do
for c, col in pairs(row) do
table.insert(sizes, col)
end
end
table.sort(sizes)
print(sizes[#sizes] * sizes[#sizes - 1] * sizes[#sizes - 2])