From 6ef26926ad9d78a236346db76dc9055ee0423252 Mon Sep 17 00:00:00 2001 From: Felix Van der Jeugt Date: Wed, 22 Dec 2021 12:48:13 +0100 Subject: [PATCH] day 22 part 2 out of memory --- day22/part2.lua | 95 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100755 day22/part2.lua diff --git a/day22/part2.lua b/day22/part2.lua new file mode 100755 index 0000000..62cd4ce --- /dev/null +++ b/day22/part2.lua @@ -0,0 +1,95 @@ +#!/usr/bin/env luajit +require("utils") + +local function r(s, e) + -- Upper borders are exclusive here! + return { s=s, e=e } +end + +local ranges = {} +for line in io.lines(arg[3]) do + local b, x0, x1, y0, y1, z0, z1 = line:match("(.*) x=(.*)%.%.(.*),y=(.*)%.%.(.*),z=(.*)%.%.(.*)") + if b == "on" then b = true else b = false end + table.insert(ranges, { + b=b, + x=r(tonumber(x0), tonumber(x1) + 1), + y=r(tonumber(y0), tonumber(y1) + 1), + z=r(tonumber(z0), tonumber(z1) + 1), + }) +end + + +local function intersect1d(a, b) + if a.e <= b.s or b.e <= a.s then + -- aaa bbb + -- bbb aaa + return { a }, {}, { b } + elseif a.s <= b.s and b.s <= a.e and a.e <= b.e then + -- aaa222bbb + return { r(a.s, b.s) }, { r(b.s, a.e) }, { r(a.e, b.e) } + elseif a.s <= b.s and b.e <= a.e then + -- aaa222aaa + return { r(a.s, b.s), r(b.e, a.e) }, { b }, {} + elseif b.s <= a.s and a.e <= b.e then + -- bbb222bbb + return {}, { a }, { r(b.s, a.s), r(a.e, b.e) } + elseif b.s <= a.s and b.e <= a.e then + -- bbb222aaa + return { r(b.e, a.e) }, { r(a.s, b.e) }, { r(b.s, a.s) } + else + error("unreachable?") + end +end + +local function cut3d(a, b) + local aparts = {} + local xas, xabs, xbs = intersect1d(a.x, b.x) + local yas, yabs, ybs = intersect1d(a.y, b.y) + local zas, zabs, zbs = intersect1d(a.z, b.z) + + local nobscombos = { { xas, yas, zas } + , { xas, yas, zabs } + , { xas, yabs, zas } + , { xas, yabs, zabs } + , { xabs, yas, zas } + , { xabs, yas, zabs } + , { xabs, yabs, zas } + } + for _, combo in pairs(nobscombos) do + local xs, ys, zs = unpack(combo) + for _, x in pairs(xs) do + for _, y in pairs(ys) do + for _, z in pairs(zs) do + table.insert(aparts, { b = a.b, x=x, y=y, z=z }) + end + end + end + end + + return aparts +end + +local fixed = { ranges[1] } +table.remove(ranges, 1) +for _, range in pairs(ranges) do + local newfixed = {} + --printtable(range) + if range.b then + table.insert(newfixed, range) + end + for _, f in pairs(fixed) do + for _, fpart in pairs(cut3d(f, range)) do + --io.write(" ") + --printtable(fpart) + table.insert(newfixed, fpart) + end + end + fixed = newfixed +end + +local count = 0 +for _, r in pairs(fixed) do + -- printtable(r) + count = count + (r.x.e - r.x.s)*(r.y.e - r.y.s)*(r.z.e - r.z.s) +end +io.write(string.format("%d\n", count))