summaryrefslogtreecommitdiff
path: root/07/2.lua
diff options
context:
space:
mode:
authorAlex Pickering <alex@cogarr.net>2025-02-07 12:49:48 -0600
committerAlex Pickering <alex@cogarr.net>2025-02-07 12:49:48 -0600
commit3555be54c2abb8d5ece008a60dbdfbde0ffbddd7 (patch)
tree278876284d07118ecdea5c48cb6453f3122887f0 /07/2.lua
downloadadvent_of_code_2022-3555be54c2abb8d5ece008a60dbdfbde0ffbddd7.tar.gz
advent_of_code_2022-3555be54c2abb8d5ece008a60dbdfbde0ffbddd7.tar.bz2
advent_of_code_2022-3555be54c2abb8d5ece008a60dbdfbde0ffbddd7.zip
inital commitHEADmaster
Diffstat (limited to '07/2.lua')
-rw-r--r--07/2.lua57
1 files changed, 57 insertions, 0 deletions
diff --git a/07/2.lua b/07/2.lua
new file mode 100644
index 0000000..93c90df
--- /dev/null
+++ b/07/2.lua
@@ -0,0 +1,57 @@
+local ds = {} -- unique value
+local pwd, tree, output = {}, {[ds]=0}, error
+local allfolders = {tree}
+local function walk(dir, path, f)
+ local cursor = dir
+ for _,v in ipairs(path) do
+ f(cursor)
+ cursor = cursor[v]
+ end
+ f(cursor)
+ return cursor
+end
+local commands = {}
+function commands.cd(arg)
+ if arg == "/" then pwd = {}
+ elseif arg == ".." then table.remove(pwd)
+ else table.insert(pwd, arg) end
+end
+function commands.ls()
+ local cursor = walk(tree, pwd, function() end)
+ output = function(line)
+ if line:match("^dir") then
+ local dirname = line:match("^dir (%w+)$")
+ cursor[dirname] = {[ds]=0}
+ table.insert(allfolders,cursor[dirname])
+ else
+ local filesize, filename = line:match("(%d+) ([%w.]+)")
+ walk(
+ tree,
+ pwd,
+ function(f) f[ds] = f[ds] + tonumber(filesize) end
+ )[filename] = filesize
+ end
+ end
+
+end
+for line in io.lines() do
+ if line:match("^%$") then
+ local line_split = {}
+ for chunk in line:gmatch("(%S+)") do
+ table.insert(line_split,chunk)
+ end
+ table.remove(line_split,1) -- remove '$'
+ -- remove command before calling it
+ commands[table.remove(line_split,1)](table.unpack(line_split))
+ else
+ output(line)
+ end
+end
+local needs = 3e7 - (7e7 - tree[ds])
+table.sort(allfolders,function(a,b) return a[ds] < b[ds] end )
+for i = 1,#allfolders do
+ if allfolders[i][ds] > needs then
+ print(allfolders[i][ds])
+ break
+ end
+end