Spiral matrix: Difference between revisions

alt impl for Lua
(Rename Perl 6 -> Raku, alphabetize, minor clean-up)
(alt impl for Lua)
Line 2,730:
 
=={{header|Lua}}==
===Original===
<lang lua>av, sn = math.abs, function(s) return s~=0 and s/av(s) or 0 end
function sindex(y, x) -- returns the value at (x, y) in a spiral that starts at 1 and goes outwards
Line 2,749 ⟶ 2,750:
 
for i,v in ipairs(spiralt(8)) do for j, u in ipairs(v) do io.write(u .. " ") end print() end</lang>
 
===Alternate===
If only the printed output is required, without intermediate array storage, then:
<lang lua>local function printspiral(n)
local function z(x,y)
local m = math.min(x, y, n-1-x, n-1-y)
return x<y and (n-2*m-2)^2+(x-m)+(y-m) or (n-2*m)^2-(x-m)-(y-m)
end
for y = 1, n do
for x = 1, n do
io.write(string.format("%2d ", n^2-z(x-1,y-1)))
end
print()
end
end
printspiral(9)</lang>
If the intermediate array storage ''is'' required, then:
<lang lua>local function makespiral(n)
local t, z = {}, function(x,y)
local m = math.min(x, y, n-1-x, n-1-y)
return x<y and (n-2*m-2)^2+(x-m)+(y-m) or (n-2*m)^2-(x-m)-(y-m)
end
for y = 1, n do t[y] = {}
for x = 1, n do t[y][x] = n^2-z(x-1,y-1) end
end
return t
end
local function printspiral(t)
for y = 1, #t do
for x = 1, #t[y] do
io.write(string.format("%2d ", t[y][x]))
end
print()
end
end
printspiral(makespiral(9))</lang>
{{out}}
(same for both)
<pre> 0 1 2 3 4 5 6 7 8
31 32 33 34 35 36 37 38 9
30 55 56 57 58 59 60 39 10
29 54 71 72 73 74 61 40 11
28 53 70 79 80 75 62 41 12
27 52 69 78 77 76 63 42 13
26 51 68 67 66 65 64 43 14
25 50 49 48 47 46 45 44 15
24 23 22 21 20 19 18 17 16</pre>
 
=={{header|Maple}}==
Anonymous user