61 lines
1.3 KiB
Lua
61 lines
1.3 KiB
Lua
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)
|