RosettaCodeData/Task/Spiral-matrix/Pluto/spiral-matrix.pluto
2026-04-30 12:34:36 -04:00

20 lines
511 B
Text

require "table2"
local fmt = require "fmt"
local function spiral_matrix(n)
local m = table.create(n)
for i = 1, n do m[i] = table.rep(n, 0) end
local dx, dy = {0, 1, 0, -1}, {1, 0, -1, 0}
local x, y, c = 0, -1, 1
for i = 0, n + n - 2 do
for j = 0, (n + n - i) // 2 - 1 do
x += dx[i % 4 + 1]
y += dy[i % 4 + 1]
m[x + 1][y + 1] = c
c += 1
end
end
return m
end
for spiral_matrix(5) as a do fmt.tprint("%2d", a, #a) end