This commit is contained in:
Felix Van der Jeugt 2021-12-14 07:52:30 +01:00
parent c8a480818f
commit e9ee2c7ac7
No known key found for this signature in database
GPG Key ID: 58B209295023754D
2 changed files with 102 additions and 0 deletions

51
day14/part1.lua Executable file
View File

@ -0,0 +1,51 @@
#!/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)

51
day14/part2.lua Executable file
View File

@ -0,0 +1,51 @@
#!/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, 40 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)