1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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
|