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

46 lines
937 B
Lua
Executable File

#!/usr/bin/env luajit
require("utils")
function readline()
local x1 = io.read("*n")
io.read(1) -- ","
local y1 = io.read("*n")
io.read(4) -- " -> "
local x2 = io.read("*n")
io.read(1) -- ","
local y2 = io.read("*n")
io.read("*l") -- "...\n"
return x1, y1, x2, y2
end
function mark(field, x, y)
local row = field[x] or {}
row[y] = (row[y] or 0) + 1
field[x] = row
end
local input = io.open(arg[3]):read("*a")
local lines = split(input, "\n")
local field = {}
for _, line in pairs(lines) do
local x1, y1, x2, y2 = unpack(split(line, "[^0-9]+"))
x1, y1, x2, y2 = tonumber(x1), tonumber(y1), tonumber(x2), tonumber(y2)
local x, y, dx, dy = x1, y1, sign(x2 - x1), sign(y2 - y1)
mark(field, x, y)
while x ~= x2 or y ~= y2 do
x, y = x + dx, y + dy
mark(field, x, y)
end
end
local count = 0
for r, row in pairs(field) do
for c, col in pairs(row) do
if col >= 2 then
count = count + 1
end
end
end
print(count)