adventofcode-2021/day14/part1.lua

52 lines
1.3 KiB
Lua
Raw Permalink Normal View History

2021-12-14 07:52:30 +01:00
#!/usr/bin/env luajit
require("utils")
local file = io.open(arg[3])
local prevchar = nil
local paircounts = {}
for char in chars(file:read("*l")) do
if prevchar ~= nil then
paircounts[prevchar..char] = (paircounts[prevchar..char] or 0) + 1
end
prevchar = char
end
file:read("*l") -- skip empty line
local line = file:read("*l")
local rules = {}
while line ~= nil do
rules[char(line, 1)..char(line, 2)] = char(line, 7)
line = file:read("*l")
end
for step = 1, 10 do
local npaircounts = {}
for pair, count in pairs(paircounts) do
if rules[pair] then
local p1, p2 = char(pair, 1)..rules[pair], rules[pair]..char(pair, 2)
npaircounts[p1] = (npaircounts[p1] or 0) + count
npaircounts[p2] = (npaircounts[p2] or 0) + count
else
npaircounts[pair] = (npaircounts[pair] or 0) + count
end
end
paircounts = npaircounts
printtable(paircounts)
end
local charcounts = {}
for pair, count in pairs(paircounts) do
charcounts[char(pair, 1)] = (charcounts[char(pair, 1)] or 0) + count
charcounts[char(pair, 2)] = (charcounts[char(pair, 2)] or 0) + count
end
foreach(charcounts, function(v) return math.ceil(v / 2) end)
printtable(charcounts)
local min, max = math.huge, 0
for char, count in pairs(charcounts) do
if count < min then min = count end
if count > max then max = count end
end
print(max - min)