@@ 1,32 1,31 @@
-local grid, R, C, E = {}, string.byte('O#.', 1, 3)
+local grid, size, R, C, E = {}, 0, string.byte('O#.', 1, -1)
io.input(arg[1])
for line in io.lines() do
- table.insert(grid, {string.byte(line, 1, #line)})
+ size = size + 1
+ grid[size] = {string.byte(line, 1, #line)}
end
-assert(#grid == #grid[1])
+assert(size == #grid[1])
local function key()
local k = {}
- for _, row in ipairs(grid) do
- table.insert(k, string.pack('z', string.char(table.unpack(row))))
+ for y, row in ipairs(grid) do
+ k[y] = string.char(table.unpack(row))
end
return table.concat(k)
end
-
-local function load()
- local l = 0
- for y, row in ipairs(grid) do
- for _, c in ipairs(row) do
- if c == R then l = l + #grid - y + 1 end
+local function load(k)
+ local i, l = 1, 0
+ for y = size, 1, -1 do
+ for _ = 1, size do
+ if string.byte(k, i) == R then l = l + y end
+ i = i + 1
end
end
return l
end
-local i, cycles, seen, cubes, last, ans1 = 1, 1000000000, {}, {}
-local size = #grid
-local cubes = {}
-while i <= cycles do
+local cycles, seen, cubes, last, ans1, ans2 = 1000000000, {}, {}
+for i = 1, cycles do
for x = 1, size do cubes[x] = 0 end
for y = 1, size do
local row = grid[y]
@@ 42,7 41,7 @@ while i <= cycles do
end
end
end
- if i == 1 then ans1 = load() end
+ if i == 1 then ans1 = load(key()) end
for y = 1, size do
local row, cube = grid[y], 0
for x = 1, size do
@@ 87,10 86,11 @@ while i <= cycles do
if not last then
local k = key()
last = seen[k]
- if last then cycles = (cycles - last) % (i - last) + i end
- seen[k] = i
+ if last then
+ ans2 = load(seen[(cycles - last) % (i - last) + last])
+ break
+ end
+ seen[k], seen[i] = i, k
end
- i = i + 1
end
-local ans2 = load()
print(ans1, ans2)