RosettaCodeData/Task/Zig-zag-matrix/Pluto/zig-zag-matrix.pluto
2026-04-30 12:34:36 -04:00

34 lines
740 B
Text

require "table2"
local fmt = require "fmt"
local function zigzag(n)
local r = table.rep(n * n, 0)
local i = 0
local n2 = n * 2
for d = 1, n2 do
local x = d - n
if x < 0 then x = 0 end
local y = d - 1
if y > n - 1 then y = n - 1 end
local j = n2 - d
if j > d then j = d end
for k = 0, j - 1 do
if d & 1 == 0 then
r[(x + k) * n + y - k + 1] = i
else
r[(y - k) * n + x + k + 1] = i
end
i += 1
end
end
return r
end
local n = 5
local w = #tostring(n * n - 1)
local i = 0
for zigzag(n) as e do
fmt.write($"%{w}d ", e)
if i % n == n - 1 then print() end
i += 1
end