advent-of-code/12022/13/13.lua

99 lines
2.0 KiB
Lua

--io.input("test")
io.input("input")
function compare(left, right)
local t = { l = type(left), r = type(right) }
if t.l == "number" and t.r == "number" then
if left < right then return true
elseif left > right then return false
else return nil
end
elseif t.l ~= t.r then
if t.l == "number" then
return compare( {left}, right )
else
return compare( left, {right} )
end
elseif t.l and t.r then -- two lists
local i = 1
while i <= #left or i <= #right do
local leftE = left[i]
local rightE = right[i]
if not rightE and leftE then
return false
elseif not leftE and rightE then
return true
end
local isCorrect = compare(leftE, rightE)
if isCorrect == nil then
i = i+1
else return isCorrect
end
end
return nil
end
end
local pair = {}
local index = 1
local count = 0
local packets = { }
for line in io.lines() do
if line == "" then
pair = {}
index = index + 1
goto continue
end
-- hehe, convert to lua table and ingest
local t = line:gsub("%[","{"):gsub("%]","}")
local s = "return " .. t
local packet = load(s)()
table.insert( packets, packet )
if not pair.l then
pair.l = packet
--print("left:", t)
else
pair.r = packet
-- print("right:", t)
local correct = compare( pair.l, pair.r )
--print("pair", index, correct)
if correct then count = count + index end
end
::continue::
end
print("part 1", count)
function tableToString(t)
local s = "{"
for i, v in ipairs(t) do
if type(v)=="table" then
s = s .. tableToString(v)
else
s = s .. tostring(v)
end
if i<#t then s = s .. "," end
end
s = s .. "}"
return s
end
-- part 2
table.insert(packets, {{2}})
table.insert(packets, {{6}})
table.sort( packets, compare )
local d1, d2
for i, p in ipairs(packets) do
local ip = p[1]
if ip and type(ip)=="table" and #ip == 1 and #p == 1 then
if ip[1] == 2 then d1 = i
elseif ip[1] == 6 then d2 = i end
end
end
print("part 2", d1*d2)