From 9a95effede4e0f03b7669d14f39c45356b19e7f7 Mon Sep 17 00:00:00 2001 From: sejo Date: Fri, 15 Dec 2023 06:51:19 +0100 Subject: [PATCH] day 15! parts 1 and 2 --- 12023/15/15.lua | 60 +++++++++++++++++++++++++++++++++++++++++++++++++ 12023/15/test | 1 + 2 files changed, 61 insertions(+) create mode 100644 12023/15/15.lua create mode 100644 12023/15/test diff --git a/12023/15/15.lua b/12023/15/15.lua new file mode 100644 index 0000000..76f0682 --- /dev/null +++ b/12023/15/15.lua @@ -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) diff --git a/12023/15/test b/12023/15/test new file mode 100644 index 0000000..62f7ed0 --- /dev/null +++ b/12023/15/test @@ -0,0 +1 @@ +rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7 \ No newline at end of file