#!/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