98 lines
2.2 KiB
Lua
98 lines
2.2 KiB
Lua
--io.input("test1")
|
|
io.input("input")
|
|
|
|
--local original = {}
|
|
--local positions = {}
|
|
local mixed = {}
|
|
local i = 0
|
|
for line in io.lines() do
|
|
local num = tonumber(line)
|
|
-- table.insert( original, num )
|
|
table.insert( mixed, { num = num, pos=i} )
|
|
i = i + 1
|
|
end
|
|
|
|
local n = #mixed
|
|
|
|
function wrap(x)
|
|
return ((x+n*10)%n)
|
|
end
|
|
|
|
for i, d in ipairs(mixed) do
|
|
if d.num == 0 then goto nextnum end
|
|
|
|
local newpos = wrap(d.pos+d.num)
|
|
--d.num<0 and (d.pos+d.num-1) or (d.pos+d.num)
|
|
--newpos = wrap(newpos)
|
|
local dir = d.num > 0
|
|
local wrapped
|
|
if dir then -- moving up
|
|
wrapped = math.abs(d.num)>n or newpos < d.pos or newpos == n-1
|
|
if wrapped then newpos = wrap(newpos + 1) end
|
|
|
|
print("checking", d.num, d.pos, newpos)
|
|
for j, t in ipairs(mixed) do
|
|
if j==i then goto continue end
|
|
|
|
if wrapped and (t.pos>=newpos and t.pos<d.pos) then
|
|
t.pos = t.pos + 1
|
|
-- print("updated", t.num, t.pos)
|
|
elseif not wrapped and (t.pos > d.pos and t.pos <= newpos) then
|
|
t.pos = t.pos - 1
|
|
-- print("updated", t.num, t.pos)
|
|
end
|
|
|
|
::continue::
|
|
end
|
|
|
|
else -- moving down
|
|
wrapped = math.abs(d.num)>n or newpos > d.pos or newpos==0
|
|
if wrapped then newpos = wrap(newpos - 1) end
|
|
|
|
|
|
print("checking", d.num, d.pos, newpos)
|
|
for j, t in ipairs(mixed) do
|
|
if j==i then goto continue end
|
|
if wrapped and (t.pos>d.pos and t.pos<=newpos) then
|
|
t.pos = t.pos - 1
|
|
-- print("updated", t.num, t.pos)
|
|
elseif not wrapped and (t.pos < d.pos and t.pos >= newpos) then
|
|
t.pos = t.pos + 1
|
|
-- print("updated", t.num, t.pos)
|
|
end
|
|
::continue::
|
|
end
|
|
end
|
|
|
|
print("changed", d.num, d.pos, newpos, dir, wrapped, i)
|
|
d.pos = newpos
|
|
|
|
::nextnum::
|
|
end
|
|
|
|
local pos0
|
|
for i, d in ipairs(mixed) do
|
|
if d.num == 0 then pos0 = d.pos break end
|
|
end
|
|
print("pos0", pos0, wrap(pos0+3000))
|
|
|
|
--[[
|
|
-- print list
|
|
table.sort(mixed, function (a,b) return a.pos < b.pos end)
|
|
local s = ""
|
|
for i, d in ipairs(mixed) do
|
|
s = s .. tostring(d.num)
|
|
if i < #mixed then s = s .. ", " end
|
|
end
|
|
print(s)
|
|
--]]
|
|
|
|
local sum = 0
|
|
for i, d in ipairs(mixed) do
|
|
if d.pos == wrap(pos0 + 1000) or d.pos == wrap(pos0+2000) or d.pos == wrap(pos0+3000) then
|
|
print(d.num)
|
|
sum = sum + d.num
|
|
end
|
|
end
|
|
print("part 1", sum)
|