summaryrefslogtreecommitdiff
path: root/07/1.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/1.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/1.lua')
-rwxr-xr-x07/1.lua53
1 files changed, 53 insertions, 0 deletions
diff --git a/07/1.lua b/07/1.lua
new file mode 100755
index 0000000..c877b9b
--- /dev/null
+++ b/07/1.lua
@@ -0,0 +1,53 @@
+#!/usr/bin/env lua
+local ds = {} -- unique value
+local pwd, tree, output = {}, {[ds]=0}, error
+local allfolders = {tree}
+--[[Walk a tree and call a function on each node]]
+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 --it's a command
+ local line_split = {}
+ line:gsub("(%S+)", function(w) table.insert(line_split,w) end)
+ table.remove(line_split, 1) -- remove '$'
+ -- remove command and call the appropriate function
+ 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