64 lines
1.3 KiB
Lua
64 lines
1.3 KiB
Lua
io.input("test")
|
|
io.input("input")
|
|
|
|
stacks = {}
|
|
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
|
|
print(nstacks)
|
|
for i = 1,nstacks do
|
|
if count == 0 then
|
|
stacks[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 )
|
|
end
|
|
elseif string.find(line, "^move") then
|
|
local pattern = "^move (%d+) from (%d+) to (%d+)$"
|
|
local t = table.pack(string.match(line, pattern))
|
|
table.insert(instructions,t)
|
|
end
|
|
count = count + 1
|
|
end
|
|
|
|
-- moves
|
|
for i, t in ipairs(instructions) do
|
|
local tt = {}
|
|
for j, v in ipairs(t) do tt[j] = tonumber(v) end
|
|
|
|
q, src, dst = table.unpack(tt)
|
|
local crates = {}
|
|
for n = 1,q do
|
|
crates[q-n+1] = table.remove( stacks[src] )
|
|
end
|
|
for n = 1,q do
|
|
table.insert( stacks[dst], crates[n] )
|
|
end
|
|
end
|
|
|
|
printStacks()
|
|
-- result
|
|
local result = ""
|
|
for _, stack in ipairs(stacks) do
|
|
result = result .. stack[#stack]
|
|
end
|
|
|
|
print("part 2", result)
|
|
|