@@ 1,6 1,7 @@
-local dirs = { -- LRUD
- [string.byte'|'] = 0x3, [string.byte'F'] = 0x5, [string.byte'L'] = 0x6,
- [string.byte'7'] = 0x9, [string.byte'J'] = 0xa, [string.byte'-'] = 0xc,
+local L, R, U, D = 1, 2, 4, 8
+local dirs = {
+ [string.byte'|'] = U|D, [string.byte'F'] = R|D, [string.byte'L'] = R|U,
+ [string.byte'7'] = L|D, [string.byte'J'] = L|U, [string.byte'-'] = L|R,
}
local S, grid, y, sx, sy = string.byte'S', {}, 1
for line in io.lines() do
@@ 13,33 14,19 @@ for line in io.lines() do
grid[y], y = row, y + 1
end
-grid[sy][sx] = (grid[sy][sx - 1] & 0x4) << 1 | (grid[sy][sx + 1] & 0x8) >> 1
- | (grid[sy - 1][sx] & 0x1) << 1 | (grid[sy + 1][sx] & 0x2) >> 1
-local x, y, dir, step = sx, sy, 0, 0
+local x, y, i, a, dir = sx, sy, 0, 0, D
+if sx > 1 and grid[sy][sx - 1] & R ~= 0 then dir = L
+elseif sx < #grid[sy] and grid[sy][sx + 1] & L ~= 0 then dir = R
+elseif sy > 1 and grid[sy - 1][sx] & D ~= 0 then dir = U
+else assert(sy < #grid and grid[sy + 1][sx] & U ~= 0) dir = D
+end
repeat
- local tile = grid[y][x]
- grid[y][x], dir = tile | 0x10, tile & ~dir
- if dir & 0x1 ~= 0 then
- y = y + 1
- elseif dir & 0x2 ~= 0 then
- y = y - 1
- elseif dir & 0x4 ~= 0 then
- x = x + 1
- elseif dir & 0x8 ~= 0 then
- x = x - 1
+ if dir == L then x, a = x - 1, a + y
+ elseif dir == R then x, a = x + 1, a - y
+ elseif dir == U then y, a = y - 1, a - x
+ else assert(dir == D) y, a = y + 1, a + x
end
- step, dir = step + 1, (dir & 0x5) << 1 | (dir & 0xa) >> 1
+ i, dir = i + 1, grid[y][x] & ~((dir & 0x5) << 1 | (dir & 0xa) >> 1)
until x == sx and y == sy
-
-local ans1, ans2 = step // 2, 0
-for y, row in ipairs(grid) do
- local inside
- for x, tile in ipairs(row) do
- if tile & 0x10 ~= 0 then
- if tile & 1 ~= 0 then inside = not inside end
- elseif inside then
- ans2 = ans2 + 1
- end
- end
-end
+local ans1, ans2 = i // 2, (math.abs(a) - i) // 2 + 1
print(ans1, ans2)