Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local grid = {} -- grid of the cucumbers
- for line in io.lines("25.txt") do
- local row = {}
- for char in line:gmatch(".") do
- table.insert(row, char)
- end
- table.insert(grid, row)
- end
- local gridCopy = {} -- copy of the grid to store the movements to be done
- for i = 1, #grid do
- local rowCopy = {}
- for j = 1, #grid[1] do
- table.insert(rowCopy, ".")
- end
- table.insert(gridCopy, rowCopy)
- end
- local canMove = {} -- grid of booleans to see if we can move
- for i = 1, #grid do
- local boolRow = {}
- for j = 1, #grid[1] do
- table.insert(boolRow, false)
- end
- table.insert(canMove, boolRow)
- end
- for n = 1, math.huge do
- local movCount = 0 -- count of movements done on a step
- for y = 1, #grid do -- check for ">" movements
- for x = 1, #grid[1] do
- if grid[y][x] == ">" and grid[y][x+1] then
- if grid[y][x+1] == "." then
- canMove[y][x] = true
- gridCopy[y][x+1] = ">"
- movCount = movCount + 1
- end
- elseif grid[y][x] == ">" and grid[y][1] == "." then
- canMove[y][x] = true
- gridCopy[y][1] = ">"
- movCount = movCount + 1
- end
- end
- end
- for y = 1, #grid do -- move them
- for x = 1, #grid[1] do
- if canMove[y][x] then
- grid[y][x] = "."
- end
- if gridCopy[y][x] == ">" then
- grid[y][x] = ">"
- end
- end
- end
- for y = 1, #gridCopy do -- clear both other tables
- for x = 1, #gridCopy[1] do
- gridCopy[y][x] = "."
- end
- end
- for y = 1, #canMove do
- for x = 1, #canMove[1] do
- canMove[y][x] = false
- end
- end
- for y = 1, #grid do -- check for "v" movements
- for x = 1, #grid[1] do
- if grid[y][x] == "v" and grid[y+1] then
- if grid[y+1][x] == "." then
- canMove[y][x] = true
- gridCopy[y+1][x] = "v"
- movCount = movCount + 1
- end
- elseif grid[y][x] == "v" and grid[1][x] == "." then
- canMove[y][x] = true
- gridCopy[1][x] = "v"
- movCount = movCount + 1
- end
- end
- end
- for y = 1, #grid do -- move them
- for x = 1, #grid[1] do
- if canMove[y][x] then
- grid[y][x] = "."
- end
- if gridCopy[y][x] == "v" then
- grid[y][x] = "v"
- end
- end
- end
- if movCount == 0 then -- if nothing has moved, break and print the solution
- print("They can't move after " .. n .. " steps")
- break
- end
- for y = 1, #gridCopy do -- clear both other tables for next iteration
- for x = 1, #gridCopy[1] do
- gridCopy[y][x] = "."
- end
- end
- for y = 1, #canMove do
- for x = 1, #canMove[1] do
- canMove[y][x] = false
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement