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

75 lines
1.6 KiB
Lua

io.input("test")
io.input("input")
stacks = {}
stacks2 = {}
instructions = {}
count = 0
function printStacks()
for i,stack in ipairs(stacks) do
local s = ""
for _,j in ipairs(stack) do
s = s .. j
end
print(i, s)
end
end
-- parsing
for line in io.lines() do
if string.find(line, "%[%a%]") then
local nstacks = #line//4 + 1 -- 1 5 9
for i = 1,nstacks do
if count == 0 then
stacks[i] = {}
stacks2[i] = {}
end
local index = 1 + (i-1)*4 -- 1, 5, 9
local s = string.sub(line, index, index+3)
local t = string.match(s, "%[(%a)%]")
table.insert( stacks[i], 1, t )
table.insert( stacks2[i], 1, t )
end
elseif string.find(line, "^move") then
local pattern = "^move (%d+) from (%d+) to (%d+)$"
local tt = table.pack(string.match(line, pattern))
local t = {}
for j, v in ipairs(tt) do t[j] = tonumber(v) end
table.insert(instructions, t)
end
count = count + 1
end
-- moves
for i, t in ipairs(instructions) do
q, src, dst = table.unpack(t)
-- part 1
for n = 1,q do
local crate = table.remove( stacks[src] )
table.insert( stacks[dst], crate )
end
-- part 2
local crates = {}
for n = 1,q do
crates[q-n+1] = table.remove( stacks2[src] )
end
for n = 1,q do
table.insert( stacks2[dst], crates[n] )
end
end
-- result
local result = ""
for _, stack in ipairs(stacks) do
result = result .. stack[#stack]
end
print("part 1", result)
result = ""
for _, stack in ipairs(stacks2) do
result = result .. stack[#stack]
end
print("part 2", result)