advent-of-code/12022/07/07.lua

93 lines
2.1 KiB
Lua

io.input("test")
io.input("input")
function createDir( dirname )
return { name = dirname, children = {}, localsize = 0}
end
function insertDirIntoWD( dirname )
-- if it already exists, return it
for _, d in ipairs( wd.children ) do
if d.name == dirname then return d end
end
-- print("inserting", dirname, "into", wd.name)
-- create it otherwise
local newdir = createDir(dirname)
table.insert( wd.children, newdir )
table.insert( dirs, newdir )
return newdir
end
-- initialize
root = createDir("/")
dirs = {root}
stack = {root}
wd = root -- working directory
local listing = false
for line in io.lines() do
if listing then
if string.find(line, "^%$") then
listing = false
else -- listing
local pattern = "^(.+) (.+)$"
local info, name = string.match( line, pattern )
if info == "dir" then
insertDirIntoWD( name )
else -- file
local size = tonumber(info)
wd.localsize = wd.localsize + size
end
end
end -- if listing
if not listing then
if string.find(line, "^%$ ls") then
listing = true
else -- change directory
local dirname = string.match(line, "^%$ cd (.+)$")
if dirname == "/" then
wd = root
stack = {root}
elseif dirname == ".." then
wd = table.remove( stack ) -- pop from stack
else -- go to named dir
table.insert( stack, wd ) -- push wd into stack
wd = insertDirIntoWD( dirname )
end -- if dirname
end -- if $ ls
end -- if not listing
end -- for line
function totalSize( dir )
local sum = dir.localsize
for i, d in ipairs( dir.children ) do
sum = sum + totalSize( d )
end
return sum
end
-- part 1
local result1 = 0
-- part 2
local total = totalSize(dirs[1])
local unused = 70000000 - total
local needed = 30000000 - unused
local minGreaterThanNeeded = total
for i, d in ipairs(dirs) do
local size = totalSize(d)
-- part 1
if size <= 100000 then
result1 = result1 + size
end
-- part 2
if size >= needed and size < minGreaterThanNeeded then
minGreaterThanNeeded = size
end
end
print("part 1", result1)
print("part 2", minGreaterThanNeeded)