@@ 1,4 1,5 @@
local grid, R, C, E = {}, string.byte('O#.', 1, 3)
+io.input(arg[1])
for line in io.lines() do
table.insert(grid, {string.byte(line, 1, #line)})
end
@@ 22,46 23,71 @@ local function load()
return l
end
-local function tilt(coord)
- local cubes = {}
- for i = 1, #grid do
- cubes[i] = 0
- end
- for j = 1, #grid do
- for i = 1, #grid do
- local x, y = coord(i, j)
- local c = grid[y][x]
+local i, cycles, seen, cubes, last, ans1 = 1, 1000000000, {}, {}
+local size = #grid
+local cubes = {}
+while i <= cycles do
+ for x = 1, size do cubes[x] = 0 end
+ for y = 1, size do
+ local row = grid[y]
+ for x = 1, size do
+ local c = row[x]
if c == C then
- cubes[i] = j
+ cubes[x] = y
elseif c == R then
- grid[y][x] = E
- local j = cubes[i] + 1
- cubes[i] = j
- x, y = coord(i, j)
+ row[x] = E
+ local y = cubes[x] + 1
+ cubes[x] = y
grid[y][x] = c
end
end
end
-end
-
-local function north(i, j) return i, j end
-local function west(i, j) return j, i end
-local function south(i, j) return i, #grid - j + 1 end
-local function east(i, j) return #grid - j + 1, i end
-
-local i, cycles, seen, cubes, last, ans1 = 1, 1000000000, {}, {}
-while i <= cycles do
- tilt(north)
if i == 1 then ans1 = load() end
- tilt(west)
- tilt(south)
- tilt(east)
+ for y = 1, size do
+ local row, cube = grid[y], 0
+ for x = 1, size do
+ local c = row[x]
+ if c == C then
+ cube = x
+ elseif c == R then
+ row[x] = E
+ cube = cube + 1
+ row[cube] = c
+ end
+ end
+ end
+ for x = 1, size do cubes[x] = size + 1 end
+ for y = size, 1, -1 do
+ local row = grid[y]
+ for x = 1, size do
+ local c = row[x]
+ if c == C then
+ cubes[x] = y
+ elseif c == R then
+ row[x] = E
+ local y = cubes[x] - 1
+ cubes[x] = y
+ grid[y][x] = c
+ end
+ end
+ end
+ for y = 1, size do
+ local row, cube = grid[y], size + 1
+ for x = size, 1, -1 do
+ local c = row[x]
+ if c == C then
+ cube = x
+ elseif c == R then
+ row[x] = E
+ cube = cube - 1
+ grid[y][cube] = c
+ end
+ end
+ end
if not last then
local k = key()
last = seen[k]
- if last then
- cycles = (cycles - last) % (i - last) + i
- end
+ if last then cycles = (cycles - last) % (i - last) + i end
seen[k] = i
end
i = i + 1