day 15! parts 1 and 2

This commit is contained in:
sejo 2023-12-15 06:51:19 +01:00
parent 46dde0d268
commit 9a95effede
2 changed files with 61 additions and 0 deletions

60
12023/15/15.lua Normal file
View File

@ -0,0 +1,60 @@
io.input("input")
function hash(s)
local curr = 0
local bytes = table.pack(s:byte(1,#s))
for i,v in ipairs(bytes) do
curr = curr + v
curr = curr*17
curr = curr%256
end
return curr
end
local line = io.read()
local sum1 = 0
function box_contains_label(b, label)
if not b or #b==0 then return nil end
for i,lens in pairs(b) do
local lab, flen = table.unpack(lens)
if lab==label then return i end
end
return nil
end
local boxes = {}
for step in line:gmatch("([^%,]+)") do
local h = hash(step)
sum1 = sum1 + h
local label,op,focal_length = step:match("([%a]+)([%p])([%d]*)")
local bxn = hash(label)
local index = box_contains_label(boxes[bxn], label)
if op=="=" then
if not boxes[bxn] then boxes[bxn] = {} end
if not index then
table.insert(boxes[bxn], table.pack(label, focal_length))
else
boxes[bxn][index] = table.pack(label, focal_length)
end
else -- "-"
if index then
table.remove(boxes[bxn], index)
end
end
end
print("part 1", sum1)
local sum2 = 0
for i,b in pairs(boxes) do
--print("BOX",i)
for j,s in ipairs(b) do
local fpower = (i+1)*j*s[2]
--print(j,table.concat(s,"->"),fpower)
sum2 = sum2 + fpower
end
end
print("part 2", sum2)

1
12023/15/test Normal file
View File

@ -0,0 +1 @@
rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7