Spiral matrix: Difference between revisions

m
 
(21 intermediate revisions by 12 users not shown)
Line 28:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F spiral_matrix(n)
V m = [[0] * n] *n
V d = [(0, 1), (1, 0), (0, -1), (-1, 0)]
Line 46:
print()
 
printspiral(spiral_matrix(5))</langsyntaxhighlight>
 
{{out}}
Line 60:
For maximum compatibility, this program uses only the basic instruction set.
{{trans|BBC BASIC}}
<langsyntaxhighlight lang="360asm">SPIRALM CSECT
USING SPIRALM,R13
SAVEAREA B STM-SAVEAREA(R15)
Line 179:
MATRIX DS H Matrix(n,n)
YREGS
END SPIRALM</langsyntaxhighlight>
{{out}}
<pre> 0 1 2 3 4
Line 186:
13 22 21 20 7
12 11 10 9 8</pre>
 
=={{header|ABAP}}==
 
<syntaxhighlight lang="abap">REPORT zspiral_matrix.
 
CLASS lcl_spiral_matrix DEFINITION FINAL.
PUBLIC SECTION.
 
TYPES:
BEGIN OF ty_coordinates,
dy TYPE i,
dx TYPE i,
value TYPE i,
END OF ty_coordinates,
ty_t_coordinates TYPE STANDARD TABLE OF ty_coordinates WITH EMPTY KEY.
 
DATA mv_dimention TYPE i.
DATA mv_initial_value TYPE i.
 
METHODS:
constructor IMPORTING iv_dimention TYPE i
iv_initial_value TYPE i,
 
get_coordinates RETURNING VALUE(rv_result) TYPE ty_t_coordinates,
 
print.
 
PRIVATE SECTION.
DATA lt_coordinates TYPE ty_t_coordinates.
 
METHODS create RETURNING VALUE(ro_result) TYPE REF TO lcl_spiral_matrix.
 
ENDCLASS.
 
CLASS lcl_spiral_matrix IMPLEMENTATION.
METHOD constructor.
 
mv_dimention = iv_dimention.
mv_initial_value = iv_initial_value.
 
create( ).
 
ENDMETHOD.
 
METHOD create.
 
DATA dy TYPE i.
DATA dx TYPE i.
DATA value TYPE i.
DATA seq_number TYPE i.
DATA seq_dimention TYPE i.
DATA sign_coef TYPE i VALUE -1.
 
value = mv_initial_value.
 
" Fill in the first row (index 0)
DO mv_dimention TIMES.
APPEND VALUE #( dy = dy dx = dx value = value ) TO lt_coordinates.
value = value + 1.
dx = dx + 1.
ENDDO.
 
seq_dimention = mv_dimention.
 
" Find the row and column numbers and set the values.
DO ( 2 * mv_dimention - 2 ) / 2 TIMES.
sign_coef = - sign_coef.
seq_dimention = seq_dimention - 1.
 
DO 2 TIMES.
seq_number = seq_number + 1.
 
DO seq_dimention TIMES.
 
IF seq_number MOD 2 <> 0.
dy = dy + 1 * sign_coef.
ELSE.
dx = dx - 1 * sign_coef.
ENDIF.
 
APPEND VALUE #( dy = dy dx = dx value = value ) TO lt_coordinates.
value = value + 1.
ENDDO.
 
ENDDO.
 
ENDDO.
 
ro_result = me.
 
ENDMETHOD.
 
METHOD get_coordinates.
rv_result = lt_coordinates.
ENDMETHOD.
 
METHOD print.
 
DATA cnt TYPE i.
DATA line TYPE string.
 
SORT lt_coordinates BY dy dx ASCENDING.
 
LOOP AT lt_coordinates ASSIGNING FIELD-SYMBOL(<ls_coordinates>).
 
cnt = cnt + 1.
line = |{ line } { <ls_coordinates>-value }|.
 
IF cnt MOD mv_dimention = 0.
WRITE / line.
CLEAR line.
ENDIF.
 
ENDLOOP.
 
ENDMETHOD.
 
ENDCLASS.
 
START-OF-SELECTION.
 
DATA(go_spiral_matrix) = NEW lcl_spiral_matrix( iv_dimention = 5
iv_initial_value = 0 ).
go_spiral_matrix->print( ).</syntaxhighlight>
 
{{out}}
<pre>
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8
</pre>
 
[https://github.com/victorizbitskiy/abapSpiralMatrix/blob/main/docs/img/Result.png Screenshot from ABAP system]
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">DEFINE MAX_SIZE="10"
DEFINE MAX_MATRIX_SIZE="100"
 
Line 256 ⟶ 391:
Test(5)
Test(6)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Spiral_matrix.png Screenshot from Atari 8-bit computer]
Line 277 ⟶ 412:
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">-- Spiral Square
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
Line 343 ⟶ 478:
begin
Print(Spiral(5));
end Spiral_Square;</langsyntaxhighlight>
The following is a variant using a different algorithm (which can also be used recursively):
<langsyntaxhighlight lang="ada">function Spiral (N : Positive) return Array_Type is
Result : Array_Type (1..N, 1..N);
Left : Positive := 1;
Line 377 ⟶ 512:
Result (Top, Left) := Index;
return Result;
end Spiral;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 384 ⟶ 519:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
<langsyntaxhighlight lang="algol68">INT empty=0;
 
PROC spiral = (INT n)[,]INT: (
Line 417 ⟶ 552:
);
print spiral(spiral(5))</langsyntaxhighlight>
{{out}}
<pre>
Line 430 ⟶ 565:
 
{{Trans|JavaScript}} (ES6)
<langsyntaxhighlight AppleScriptlang="applescript">---------------------- SPIRAL MATRIX ---------------------
 
-- spiral :: Int -> [[Int]]
Line 686 ⟶ 821:
on unwords(xs)
intercalateS(space, xs)
end unwords</langsyntaxhighlight>
{{Out}}
{| class="wikitable" style="text-align:center;width:12em;height:12em;table-layout:fixed;"
Line 700 ⟶ 835:
| 12 || 11 || 10 || 9 || 8
|}
 
=={{header|Arturo}}==
{{trans|Python}}
<syntaxhighlight lang="rebol">spiralMatrix: function [n][
m: new array.of: @[n,n] null
 
[dx, dy, x, y]: [1, 0, 0, 0]
 
loop 0..dec n^2 'i [
m\[y]\[x]: i
 
[nx,ny]: @[x+dx, y+dy]
 
if? and? [and? [in? nx 0..n-1][in? ny 0..n-1]][
null? m\[ny]\[nx]
][
[x,y]: @[nx, ny]
]
else [
bdx: dx
[dx, dy]: @[neg dy, bdx]
[x, y]: @[x+dx, y+dy]
]
]
 
return m
]
 
loop spiralMatrix 5 'row [
print map row 'x -> pad to :string x 4
]</syntaxhighlight>
 
{{out}}
 
<pre> 0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8</pre>
 
=={{header|AutoHotkey}}==
{{trans|Python|}}
ahk forum: [http://www.autohotkey.com/forum/post-276718.html#276718 discussion]
<langsyntaxhighlight AutoHotkeylang="autohotkey">n := 5, dx := x := y := v := 1, dy := 0
 
Loop % n*n {
Line 729 ⟶ 903:
13 12 11 10 9
---------------------------
*/</langsyntaxhighlight>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f SPIRAL_MATRIX.AWK [-v offset={0|1}] [size]
# converted from BBC BASIC
Line 772 ⟶ 946:
exit(0)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 783 ⟶ 957:
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> N%=5
@%=LENSTR$(N%*N%-1)+1
BotCol%=0 : TopCol%=N%-1
Line 800 ⟶ 974:
ENDCASE
NEXT
END</langsyntaxhighlight>
 
=={{header|C}}==
Note: program produces a matrix starting from 1 instead of 0, because task says "natural numbers".
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
Line 838 ⟶ 1,012:
 
return 0;
}</langsyntaxhighlight>
 
Recursive method, width and height given on command line:
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 858 ⟶ 1,032:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
Solution based on the [[#J|J]] hints:
<langsyntaxhighlight lang="csharp">public int[,] Spiral(int n) {
int[,] result = new int[n, n];
 
Line 898 ⟶ 1,072:
Console.WriteLine();
}
}</langsyntaxhighlight>
 
Translated proper C++ solution:
<langsyntaxhighlight lang="csharp">
 
//generate spiral matrix for given N
Line 924 ⟶ 1,098:
}
}
</syntaxhighlight>
</lang>
 
====Spiral Matrix without using an Array====
 
<langsyntaxhighlight lang="csharp">
using System;
using System.Collections.Generic;
Line 1,000 ⟶ 1,174:
}
}
</syntaxhighlight>
</lang>
{{Out}}
<langsyntaxhighlight lang="sh">INPUT:-
 
Enter order..
Line 1,032 ⟶ 1,206:
17 30 29 28 27 10
16 15 14 13 12 11
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <vector>
#include <memory> // for auto_ptr
#include <cmath> // for the ceil and log10 and floor functions
Line 1,101 ⟶ 1,275:
{
printSpiralArray( getSpiralArray( 5 ) );
}</langsyntaxhighlight>
 
C++ solution done properly:
<langsyntaxhighlight lang="cpp">#include <vector>
#include <iostream>
using namespace std;
Line 1,120 ⟶ 1,294:
cout << endl;
}
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
Based on the [[#J|J]] hints (almost as incomprehensible, maybe)
<langsyntaxhighlight lang="clojure">(defn spiral [n]
(let [cyc (cycle [1 n -1 (- n)])]
(->> (range (dec n) 0 -1)
Line 1,139 ⟶ 1,313:
true
(str " ~{~<~%~," (* n 3) ":;~2d ~>~}~%")
(spiral n)))</langsyntaxhighlight>
Recursive generation:
{{trans|Common Lisp}}
<langsyntaxhighlight lang="clojure">
(defn spiral-matrix [m n & [start]]
(let [row (list (map #(+ start %) (range m)))]
Line 1,151 ⟶ 1,325:
 
(defn spiral [n m] (spiral-matrix n m 1))
</syntaxhighlight>
</lang>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
# Let's say you want to arrange the first N-squared natural numbers
# in a spiral, where you fill in the numbers clockwise, starting from
Line 1,201 ⟶ 1,375:
console.log "\n----Spiral n=#{n}"
console.log spiral_matrix n
</syntaxhighlight>
</lang>
{{out}}
<syntaxhighlight lang="text">
> coffee spiral.coffee
 
Line 1,222 ⟶ 1,396:
[ 19, 36, 35, 34, 33, 32, 11 ],
[ 18, 17, 16, 15, 14, 13, 12 ] ]
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
{{trans|Python}}
<langsyntaxhighlight lang="lisp">(defun spiral (rows columns)
(do ((N (* rows columns))
(spiral (make-array (list rows columns) :initial-element nil))
Line 1,243 ⟶ 1,417:
dy dx)
(setf x (+ x dx)
y (+ y dy)))))))</langsyntaxhighlight>
<pre>> (pprint (spiral 6 6))
 
Line 1,261 ⟶ 1,435:
(8 7 6))</pre>
Recursive generation:
<langsyntaxhighlight lang="lisp">(defun spiral (m n &optional (start 1))
(let ((row (list (loop for x from 0 to (1- m) collect (+ x start)))))
(if (= 1 n) row
Line 1,271 ⟶ 1,445:
;; test
(loop for row in (spiral 4 3) do
(format t "~{~4d~^~}~%" row))</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.stdio;
enum n = 5;
Line 1,293 ⟶ 1,467:
 
writefln("%(%(%2d %)\n%)", M);
}</langsyntaxhighlight>
{{out}}
<pre> 0 1 2 3 4
Line 1,301 ⟶ 1,475:
12 11 10 9 8</pre>
Using a generator for any rectangular array:
<langsyntaxhighlight lang="d">import std.stdio;
 
/// 2D spiral generator
Line 1,352 ⟶ 1,526:
foreach (r; spiralMatrix(9, 4))
writefln("%(%2d %)", r);
}</langsyntaxhighlight>
{{out}}
<pre> 0 1 2 3 4 5 6 7 8
Line 1,360 ⟶ 1,534:
 
=={{header|DCL}}==
<langsyntaxhighlight DCLlang="dcl">$ p1 = f$integer( p1 )
$ max = p1 * p1
$
Line 1,415 ⟶ 1,589:
$ endif
$ endif
$ return</langsyntaxhighlight>
{{out}}
<pre>$ @spiral_matrix 3
Line 1,429 ⟶ 1,603:
 
...</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls, Windows}}
This code actually creates a matrix in memory and stores values in the matrix, instead of just simulating one by drawing the pattern. It can also create matrices of any size and the matrices don't have to be square. It works by creating a rectangle of the same size as the matrix. It enters the values in the matrix along circumference of the matrix. It then uses the Windows library routine "InflateRect" to decrease the size of the rectangle until the whole matrix is filled with spiraling values. Since a rectangle can be any size and doesn't have to be square, it works with any size matrix, including non-square matrices.
 
<syntaxhighlight lang="Delphi">
 
 
type TMatrix = array of array of double;
 
 
procedure DisplayMatrix(Memo: TMemo; Mat: TMatrix);
{Display specified matrix}
var X,Y: integer;
var S: string;
begin
S:='';
for Y:=0 to High(Mat[0]) do
begin
S:=S+'[';
for X:=0 to High(Mat) do
S:=S+Format('%4.0f',[Mat[X,Y]]);
S:=S+']'+#$0D#$0A;
end;
Memo.Lines.Add(S);
end;
 
 
procedure MakeSpiralMatrix(var Mat: TMatrix; SizeX,SizeY: integer);
{Create a spiral matrix of specified size}
var Inx: integer;
var R: TRect;
 
procedure DoRect(R: TRect; var Inx: integer);
{Create on turn of the spiral base on the rectangle}
var X,Y: integer;
begin
{Do top part of rectangle}
for X:=R.Left to R.Right do
begin
Mat[X,R.Top]:=Inx;
Inc(Inx);
end;
{Do Right part of rectangle}
for Y:=R.Top+1 to R.Bottom do
begin
Mat[R.Right,Y]:=Inx;
Inc(Inx);
end;
{Do bottom part of rectangle}
for X:= R.Right-1 downto R.Left do
begin
Mat[X,R.Bottom]:=Inx;
Inc(Inx);
end;
{Do left part of rectangle}
for Y:=R.Bottom-1 downto R.Top+1 do
begin
Mat[R.Left,Y]:=Inx;
Inc(Inx);
end;
end;
 
begin
{Set matrix size}
SetLength(Mat,SizeX,SizeY);
{create matching rectangle}
R:=Rect(0,0,SizeX-1,SizeY-1);
Inx:=0;
{draw and deflate rectangle until spiral is done}
while (R.Left<=R.Right) and (R.Top<=R.Bottom) do
begin
DoRect(R,Inx);
InflateRect(R,-1,-1);
end;
end;
 
 
 
procedure SpiralMatrix(Memo: TMemo);
{Display spiral matrix}
var Mat: TMatrix;
begin
Memo.Lines.Add('5x5 Matrix');
MakeSpiralMatrix(Mat,5,5);
DisplayMatrix(Memo,Mat);
 
Memo.Lines.Add('8x8 Matrix');
MakeSpiralMatrix(Mat,8,8);
DisplayMatrix(Memo,Mat);
 
Memo.Lines.Add('14x8 Matrix');
MakeSpiralMatrix(Mat,14,8);
DisplayMatrix(Memo,Mat);
end;
</syntaxhighlight>
{{out}}
<pre>
5x5 Matrix
[ 0 1 2 3 4]
[ 15 16 17 18 5]
[ 14 23 24 19 6]
[ 13 22 21 20 7]
[ 12 11 10 9 8]
 
8x8 Matrix
[ 0 1 2 3 4 5 6 7]
[ 27 28 29 30 31 32 33 8]
[ 26 47 48 49 50 51 34 9]
[ 25 46 59 60 61 52 35 10]
[ 24 45 58 63 62 53 36 11]
[ 23 44 57 56 55 54 37 12]
[ 22 43 42 41 40 39 38 13]
[ 21 20 19 18 17 16 15 14]
 
14x8 Matrix
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13]
[ 39 40 41 42 43 44 45 46 47 48 49 50 51 14]
[ 38 71 72 73 74 75 76 77 78 79 80 81 52 15]
[ 37 70 95 96 97 98 99 100 101 102 103 82 53 16]
[ 36 69 94 111 110 109 108 107 106 105 104 83 54 17]
[ 35 68 93 92 91 90 89 88 87 86 85 84 55 18]
[ 34 67 66 65 64 63 62 61 60 59 58 57 56 19]
[ 33 32 31 30 29 28 27 26 25 24 23 22 21 20]
 
Elapsed Time: 11.242 ms.
 
</pre>
 
=={{header|E}}==
Line 1,434 ⟶ 1,737:
 
{{E 2D utilities}}
<langsyntaxhighlight lang="e">def spiral(size) {
def array := makeFlex2DArray(size, size)
var i := -1 # Counter of numbers to fill
Line 1,458 ⟶ 1,761:
return array
}</langsyntaxhighlight>
Example:
<langsyntaxhighlight lang="e">? print(spiral(5))
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight>
proc mkspiral n . t[] .
subr side
for i to l
ind += d
t[ind] = cnt
cnt += 1
.
.
len t[] n * n
l = n
while cnt < len t[]
d = 1
side
l -= 1
d = n
side
d = -1
side
l -= 1
d = -n
side
.
.
n = 5
mkspiral n t[]
numfmt 0 3
for i to n * n
write t[i]
if i mod n = 0
print ""
.
.
</syntaxhighlight>
{{out}}
<pre>
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8
</pre>
 
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule RC do
def spiral_matrix(n) do
wide = length(to_char_list(n*n-1))
Line 1,487 ⟶ 1,834:
end
 
RC.spiral_matrix(5)</langsyntaxhighlight>
 
'''The other way'''
<langsyntaxhighlight lang="elixir">defmodule RC do
def spiral_matrix(n) do
wide = String.length(to_string(n*n-1))
Line 1,519 ⟶ 1,866:
end
 
RC.spiral_matrix(5)</langsyntaxhighlight>
 
'''Another way'''
<langsyntaxhighlight lang="elixir">defmodule RC do
def spiral_matrix(n) do
fmt = String.duplicate("~#{length(to_char_list(n*n-1))}w ", n) <> "~n"
Line 1,540 ⟶ 1,887:
end
 
RC.spiral_matrix(5)</langsyntaxhighlight>
 
{{out}}
Line 1,552 ⟶ 1,899:
 
=={{header|Euphoria}}==
<langsyntaxhighlight Euphorialang="euphoria">function spiral(integer dimension)
integer side, curr, curr2
sequence s
Line 1,580 ⟶ 1,927:
end function
 
? spiral(5)</langsyntaxhighlight>
 
{{out}}
Line 1,593 ⟶ 1,940:
=={{header|F_Sharp|F#}}==
No fancy schmancy elegance here, just putting the numbers in the right place (though I commend the elegance)...
<langsyntaxhighlight lang="fsharp">let Spiral n =
let sq = Array2D.create n n 0 // Set up an output array
let nCur = ref -1 // Current value being inserted
Line 1,606 ⟶ 1,953:
[0..(n/2 - 1)] |> Seq.iter (fun i -> Frame i) // Fill in all frames
if n &&& 1 = 1 then sq.[n/2,n/2] <- n*n - 1 // If n is odd, fill in the last single value
sq // Return our output array</langsyntaxhighlight>
 
=={{header|Factor}}==
This is an implementation of Joey Tuttle's method for computing a spiral directly as a list and then reshaping it into a matrix, as described in the [http://rosettacode.org/wiki/Spiral_matrix#J J entry]. To summarize, we construct a list with <code>n*n</code> elements by following some simple rules, then take its cumulative sum, and finally its inverse permutation (or grade in J parlance). This gives us a list which can be reshaped to the final matrix.
<langsyntaxhighlight lang="factor">USING: arrays grouping io kernel math math.combinatorics
math.ranges math.statistics prettyprint sequences
sequences.repeating ;
Line 1,628 ⟶ 1,975:
: spiral-demo ( -- ) 5 9 [ spiral simple-table. nl ] bi@ ;
 
MAIN: spiral-demo</langsyntaxhighlight>
{{out}}
<pre>
Line 1,650 ⟶ 1,997:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">PROGRAM SPIRAL
 
IMPLICIT NONE
Line 1,698 ⟶ 2,045:
END DO
 
END PROGRAM SPIRAL</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Enum Direction
Line 1,776 ⟶ 2,123:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,790 ⟶ 2,137:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># Spiral matrix with numbers 1 .. n<sup>2</sup>, more natural in GAP
SpiralMatrix := function(n)
local i, j, k, di, dj, p, vi, vj, imin, imax, jmin, jmax;
Line 1,836 ⟶ 2,183:
# [ 15, 24, 25, 20, 7 ],
# [ 14, 23, 22, 21, 8 ],
# [ 13, 12, 11, 10, 9 ] ]</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,896 ⟶ 2,243:
}
}
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Naive "path-walking" solution:
<langsyntaxhighlight lang="groovy">enum Direction {
East([0,1]), South([1,0]), West([0,-1]), North([-1,0]);
private static _n
Line 1,953 ⟶ 2,300:
}
M
}</langsyntaxhighlight>
Test:
<langsyntaxhighlight lang="groovy">(1..10).each { n ->
spiralMatrix(n).each { row ->
row.each { printf "%5d", it }
Line 1,961 ⟶ 2,308:
}
println ()
}</langsyntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll;"> 0
Line 2,030 ⟶ 2,377:
=={{header|Haskell}}==
Solution based on the [[#J|J]] hints:
<langsyntaxhighlight lang="haskell">import Data.List
import Control.Monad
grade xs = map snd. sort $ zip xs [0..]
Line 2,038 ⟶ 2,385:
spiral n = reshape n . grade. scanl1 (+). concat $ zipWith replicate (counts n) (values n)
displayRow = putStrLn . intercalate " " . map show
main = mapM displayRow $ spiral 5</langsyntaxhighlight>
 
An alternative, point-free solution based on the same J source.
 
<langsyntaxhighlight lang="haskell">import Data.List
import Control.Applicative
counts = tail . reverse . concat . map (replicate 2) . enumFromTo 1
Line 2,050 ⟶ 2,397:
parts = (<*>) take $ (.) <$> (map . take) <*> (iterate . drop) <*> copies
disp = (>> return ()) . mapM (putStrLn . intercalate " " . map show) . parts
main = disp 5</langsyntaxhighlight>
 
Another alternative:
<langsyntaxhighlight lang="haskell">import Data.List (transpose)
import Text.Printf (printf)
 
Line 2,062 ⟶ 2,409:
 
-- this is sort of hideous, someone may want to fix it
main = mapM_ (\row->mapM_ ((printf "%4d").toInteger) row >> putStrLn "") (spiral 10 9 1)</langsyntaxhighlight>
 
 
Or less ambitiously,
{{Trans|AppleScript}}
<langsyntaxhighlight Haskelllang="haskell">import Data.List (intercalate, transpose)
 
---------------------- SPIRAL MATRIX ---------------------
Line 2,096 ⟶ 2,443:
. (<> "\n|}")
. intercalate "\n|-\n"
. fmap (('|' :) . (' ' :) . intercalate " || " . fmap show)</langsyntaxhighlight>
{{Out}}
{| class="wikitable" style="text-align: right;width:12em;height:12em;table-layout:fixed;"|-
Line 2,112 ⟶ 2,459:
=={{header|Icon}} and {{header|Unicon}}==
At first I looked at keeping the filling of the matrix on track using /M[r,c] which fails when out of bounds or if the cell is null, but then I noticed the progression of the row and column increments from corner to corner reminded me of sines and cosines. I'm not sure if the use of a trigonometric function counts as elegance, perversity, or both. The generator could be easily modified to start at an arbitrary corner. Or count down to produce and evolute.
<langsyntaxhighlight Iconlang="icon">procedure main(A) # spiral matrix
N := 0 < integer(\A[1]|5) # N=1... (dfeault 5)
WriteMatrix(SpiralMatrix(N))
Line 2,139 ⟶ 2,486:
}
return M
end</langsyntaxhighlight>
 
{{out}}
Line 2,149 ⟶ 2,496:
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "SpiralMa.bas"
110 TEXT 80
120 INPUT PROMPT "Enter size of matrix (max. 10): ":N
Line 2,194 ⟶ 2,541:
530 PRINT
540 NEXT
550 END DEF</langsyntaxhighlight>
 
=={{header|J}}==
This function is the result of
some [http://www.jsoftware.com/papers/play132.htm beautiful insights]:
<langsyntaxhighlight lang="j">spiral =: ,~ $ [: /: }.@(2 # >:@i.@-) +/\@# <:@+: $ (, -)@(1&,)
 
spiral 5
Line 2,206 ⟶ 2,553:
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8</langsyntaxhighlight>
Would you like [[Talk:Spiral#J|some hints]] that will allow you to reimplement it in another language?
 
Line 2,214 ⟶ 2,561:
{{trans|C++}}
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">public class Blah {
 
public static void main(String[] args) {
Line 2,264 ⟶ 2,611:
}
}
}</langsyntaxhighlight>
{{out}}
<pre> 0 1 2 3 4
Line 2,276 ⟶ 2,623:
===Imperative===
 
<langsyntaxhighlight lang="javascript">spiralArray = function (edge) {
var arr = Array(edge),
x = 0, y = edge,
Line 2,297 ⟶ 2,644:
arr = spiralArray(edge = 5);
for (y= 0; y < edge; y++) console.log(arr[y].join(" "));
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,312 ⟶ 2,659:
Translating one of the Haskell versions:
 
<langsyntaxhighlight JavaScriptlang="javascript">(function (n) {
 
// Spiral: the first row plus a smaller spiral rotated 90 degrees clockwise
Line 2,378 ⟶ 2,725:
].join('\n\n');
 
})(5);</langsyntaxhighlight>
 
Output:
Line 2,395 ⟶ 2,742:
|}
 
<langsyntaxhighlight JavaScriptlang="javascript">[[0,1,2,3,4],[15,16,17,18,5],[14,23,24,19,6],[13,22,21,20,7],[12,11,10,9,8]]</langsyntaxhighlight>
 
 
====ES6====
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'"use strict'";
 
// ------------------ SPIRAL MATRIX ------------------
// main :: () -> String
const main = () =>
unlines(
map(unwords, spiral(5))
);
 
// spiral :: Int -> [[Int]]
const spiral = n => {
const go = (rows, cols, start) =>
0 < Boolean(rows) ? [
enumFromTo(start, )(start + pred(cols)),
...maptranspose(
reverse,go(
transpose( cols,
gopred(rows),
start + cols,
pred(rows),
start + cols
)
)
).map(reverse)
] : [
[]
];
 
return go(n, n, 0);
};
 
// GENERIC FUNCTIONS ----------------------------------
 
// ---------------------- TEST -----------------------
// comparing :: (a -> b) -> (a -> a -> Ordering)
const// comparingmain =:: f() =-> String
const main = (x, y) => {
const
an = f(x)5,
cellWidth = 1 + b`${pred(n =** f(y2)}`.length;
return a < b ? -1 : (a > b ? 1 : 0);
};
 
return unlines(
// concatMap :: (a -> [b]) -> [a] -> [b]
spiral(n).map(
const concatMap = (f, xs) =>
0 < xs.length ? (() row => {(
const unit = 'string' !== typeof xs ? row.map(x => `${x}`
[] .padStart(cellWidth, " "))
) : ''; )
return unit.concat.apply(unit, xs .mapjoin(f)"")
})() : []; )
);
 
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = (m, n) =>
m <= n ? iterateUntil(
x => n <= x,
x => 1 + x,
m
) : [];
 
// iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]
const iterateUntil = (p, f, x) => {
const vs = [x];
let h = x;
while (!p(h))(h = f(h), vs.push(h));
return vs;
};
 
// length :: [a] -> Int
const length = xs => xs.length;
 
// --------------------- GENERIC ---------------------
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f);
 
// enumFromTo :: Int -> Int -> [Int]
// Ordering: (LT|EQ|GT):
const enumFromTo = m =>
// GT: 1 (or other positive n)
// EQ:n 0=> Array.from({
// LT length: -1 (or+ othern negative- n)m
}, (_, i) => m + i);
 
// maximumBy :: (a -> a -> Ordering) -> [a] -> a
const maximumBy = (f, xs) =>
0 < xs.length ? (
xs.slice(1)
.reduce((a, x) => 0 < f(x, a) ? x : a, xs[0])
) : undefined;
 
 
// pred :: Enum a => a -> a
const pred = x => x - 1;
 
 
// reverse :: [a] -> [a]
const reverse = xs =>
'"string'" !=== typeof xs ? (
xs.slicesplit(0"").reverse()
) : xs.split('').reverse() .join(''"");
) : xs.slice(0).reverse();
 
// replicate :: Int -> a -> [a]
const replicate = (n, x) =>
Array.from({
length: n
}, () => x);
 
// transpose :: [[a]] -> [[a]]
const transpose = tblrows => {
// The columns of the input transposed
const
// into new gaps = replicate(rows.
// Simpler version of transpose, assuming input
length(maximumBy(comparing(length), tbl)), []
// rows of even ),length.
Boolean(rows.length) ? rows = [0].map(xs => xs.concat(gaps.slice(xs.length)), tbl);
return map (_, i) => rows.flatMap(
(_, col) => concatMap(row v => v[row[coli]], rows),
rows[0])
) : [];
 
};
 
// unlines :: [String] -> String
const unlines = xs => xs.join('\n');
// A single string formed by the intercalation
// of a list of strings with the newline character.
xs.join("\n");
 
// unwords :: [String] -> String
const unwords = xs => xs.join(' ');
 
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre> 0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8</pre>
 
=={{header|jq}}==
Line 2,536 ⟶ 2,849:
 
'''Infrastructure''':
<langsyntaxhighlight lang="jq"># Create an m x n matrix
def matrix(m; n; init):
if m == 0 then []
Line 2,561 ⟶ 2,874:
elif . == [0, 1] then [ 1, 0]
else error("invalid direction: \(.)")
end;</langsyntaxhighlight>
'''Create a spiral n by n matrix'''
<langsyntaxhighlight lang="jq">def spiral(n):
# we just placed m at i,j, and we are moving in the direction d
def _next(i; j; m; d):
Line 2,576 ⟶ 2,889:
 
# Example
spiral(5) | neatly(3)</langsyntaxhighlight>
{{Out}}
$ jq -n -r -f spiral.jq
Line 2,589 ⟶ 2,902:
 
'''Spiral Matrix Iterator'''
<syntaxhighlight lang="julia">
<lang Julia>
immutable Spiral
m::Int
Line 2,633 ⟶ 2,946:
return (s, sps)
end
</syntaxhighlight>
</lang>
 
'''Helper Functions'''
<syntaxhighlight lang="julia">
<lang Julia>
using Formatting
 
Line 2,661 ⟶ 2,974:
return s
end
</syntaxhighlight>
</lang>
 
'''Main'''
<syntaxhighlight lang="julia">
<lang Julia>
n = 5
println("The n = ", n, " spiral matrix:")
Line 2,691 ⟶ 3,004:
end
println(pretty(a))
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,719 ⟶ 3,032:
=={{header|Kotlin}}==
{{trans|C#}}
<langsyntaxhighlight lang="scala">// version 1.1.3
 
typealias Vector = IntArray
Line 2,758 ⟶ 3,071:
printMatrix(spiralMatrix(5))
printMatrix(spiralMatrix(10))
}</langsyntaxhighlight>
 
{{out}}
Line 2,782 ⟶ 3,095:
=={{header|Liberty BASIC}}==
Extended to include automatic scaling of the display scale and font. See [http://www.diga.me.uk/spiralM5.gif spiralM5]
<langsyntaxhighlight lang="lb">nomainwin
 
UpperLeftX = 50
Line 2,857 ⟶ 3,170:
[quit]
close #w
end</langsyntaxhighlight>
 
=={{header|Lua}}==
===Original===
<langsyntaxhighlight 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
if y == -x and y >= x then return (2*y+1)^2 end
Line 2,879 ⟶ 3,192:
end
 
for i,v in ipairs(spiralt(8)) do for j, u in ipairs(v) do io.write(u .. " ") end print() end</langsyntaxhighlight>
 
===Alternate===
If only the printed output is required, without intermediate array storage, then:
<langsyntaxhighlight lang="lua">local function printspiral(n)
local function z(x,y)
local m = math.min(x, y, n-1-x, n-1-y)
Line 2,895 ⟶ 3,208:
end
end
printspiral(9)</langsyntaxhighlight>
If the intermediate array storage ''is'' required, then:
<langsyntaxhighlight lang="lua">local function makespiral(n)
local t, z = {}, function(x,y)
local m = math.min(x, y, n-1-x, n-1-y)
Line 2,915 ⟶ 3,228:
end
end
printspiral(makespiral(9))</langsyntaxhighlight>
{{out}}
(same for both)
Line 2,930 ⟶ 3,243:
=={{header|Maple}}==
 
<syntaxhighlight lang="maple">
<lang Maple>
with(ArrayTools):
 
Line 2,958 ⟶ 3,271:
spiralArray(5);
 
</syntaxhighlight>
</lang>
{{out}}<pre>
[ 0 1 2 3 4]
Line 2,974 ⟶ 3,287:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
We split the task up in 2 functions, one that adds a 'ring' around a present matrix. And a function that adds rings to a 'core':
<langsyntaxhighlight Mathematicalang="mathematica">AddSquareRing[x_List/;Equal@@Dimensions[x] && Length[Dimensions[x]]==2]:=Module[{new=x,size,smallest},
size=Length[x];
smallest=x[[1,1]];
Line 2,989 ⟶ 3,302:
times=If[Mod[size,2]==0,size/2-1,(size-1)/2];
Nest[AddSquareRing,start,times]
]</langsyntaxhighlight>
Examples:
<langsyntaxhighlight Mathematicalang="mathematica">MakeSquareSpiral[2] // MatrixForm
MakeSquareSpiral[7] // MatrixForm</langsyntaxhighlight>
gives back:
<math>
Line 3,023 ⟶ 3,336:
<math>(-spiral(n))+n^2</math>
Then depending on if n is odd or even we use either an up/down or left/right mirror transformation.
<langsyntaxhighlight MATLABlang="matlab">function matrix = reverseSpiral(n)
matrix = (-spiral(n))+n^2;
Line 3,033 ⟶ 3,346:
end
end %reverseSpiral</langsyntaxhighlight>
Sample Usage:
<langsyntaxhighlight MATLABlang="matlab">>> reverseSpiral(5)
 
ans =
Line 3,043 ⟶ 3,356:
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">spiral(n) := block([a, i, j, k, p, di, dj, vi, vj, imin, imax, jmin, jmax],
a: zeromatrix(n, n),
vi: [1, 0, -1, 0],
Line 3,085 ⟶ 3,398:
[15, 24, 25, 20, 7],
[14, 23, 22, 21, 8],
[13, 12, 11, 10, 9]) */</langsyntaxhighlight>
 
=={{header|MiniZinc}}==
<syntaxhighlight lang="minizinc">
<lang MiniZinc>
%Spiral Matrix. Nigel Galloway, February 3rd., 2020
int: Size;
Line 3,097 ⟶ 3,410:
constraint forall(n in 1..Size div 2)(forall(g in n..Size-n)(spiral[Size-n+1,g]=spiral[Size-n+1,g+1]+1)) /\ forall(n in 1..Size div 2)(forall(g in n+1..Size-n)(spiral[g,n]=spiral[g+1,n]+1));
output [show2d(spiral)];
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,130 ⟶ 3,443:
=={{header|NetRexx}}==
{{Trans|ooRexx}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
 
Line 3,222 ⟶ 3,535:
return maxNum
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,243 ⟶ 3,556:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import sequtils, strutils
 
proc `$`(m: seq[seq[int]]): string =
Line 3,269 ⟶ 3,582:
y += dy
 
echo spiral(5)</langsyntaxhighlight>
{{out}}
<pre> 0 1 2 3 4
Line 3,278 ⟶ 3,591:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let next_dir = function
| 1, 0 -> 0, -1
| 0, 1 -> 1, 0
Line 3,316 ⟶ 3,629:
print_newline())
 
let () = print(spiral 5)</langsyntaxhighlight>
 
Another implementation:
<langsyntaxhighlight lang="ocaml">let spiral n =
let ar = Array.make_matrix n n (-1) in
let out i = i < 0 || i >= n in
Line 3,335 ⟶ 3,648:
Array.iter (fun v -> Array.iter (Printf.printf " %2d") v; print_newline())
 
let _ = show (spiral 5)</langsyntaxhighlight>
 
=={{header|Octave}}==
{{trans|Stata}}
<langsyntaxhighlight lang="octave">function a = spiral(n)
a = ones(n*n, 1);
u = -(i = n) * (v = ones(n, 1));
Line 3,359 ⟶ 3,672:
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8</langsyntaxhighlight>
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
<lang ooRexx>
call printArray generateArray(3)
say
Line 3,418 ⟶ 3,731:
say line
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,439 ⟶ 3,752:
=={{header|Oz}}==
Simple, recursive solution:
<langsyntaxhighlight lang="oz">declare
fun {Spiral N}
%% create nested array
Line 3,480 ⟶ 3,793:
end
in
{Inspect {Spiral 5}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
 
<langsyntaxhighlight lang="parigp">spiral(dim) = {
my (M = matrix(dim, dim), p = s = 1, q = i = 0);
for (n=1, dim,
Line 3,492 ⟶ 3,805:
);
M
}</langsyntaxhighlight>
 
Output:<pre>spiral(7)
Line 3,511 ⟶ 3,824:
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">program Spiralmat;
type
tDir = (left,down,right,up);
Line 3,581 ⟶ 3,894:
end;
END.
</syntaxhighlight>
</lang>
{{out}}
<pre> 1
Line 3,596 ⟶ 3,909:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub spiral
{my ($n, $x, $y, $dx, $dy, @a) = (shift, 0, 0, 1, 0);
foreach (0 .. $n**2 - 1)
Line 3,616 ⟶ 3,929:
foreach (spiral 5)
{printf "%3d", $_ foreach @$_;
print "\n";}</langsyntaxhighlight>
 
=={{header|Phix}}==
{{Transtrans|Python}}
Simple is better.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>integer n = 5
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
string fmt = sprintf("%%%dd",length(sprintf("%d",n*n)))
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">counter</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span>
integer x = 1, y = 0, c = 0, dx = 0, dy = 1, len = n
<span style="color: #000000;">len</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dx</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dy</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
sequence m = repeat(repeat("??",n),n)
<span style="color: #004080;">string</span> <span style="color: #000000;">fmt</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%%%dd"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%d"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">*</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)))</span>
for i=1 to 2*n do -- 2n runs..
<span style="color: #004080;">sequence</span> <span style="color: #000000;">m</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"??"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">),</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
for j=1 to len do -- of a length...
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">n</span> <span style="color: #008080;">do</span> <span style="color: #000080;font-style:italic;">-- 2n runs..</span>
x += dx
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">len</span> <span style="color: #008080;">do</span> <span style="color: #000080;font-style:italic;">-- of a length...</span>
y += dy
<span style="color: #000000;">x</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">dx</span>
m[x][y] = sprintf(fmt,c)
<span style="color: #000000;">y</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">dy</span>
c += 1
<span style="color: #000000;">m</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span><span style="color: #0000FF;">][</span><span style="color: #000000;">y</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">counter</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #000000;">counter</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
len -= and_bits(i,1) -- ..-1 every other
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
{dx,dy} = {dy,-dx} -- in new direction
<span style="color: #000000;">len</span> <span style="color: #0000FF;">-=</span> <span style="color: #7060A8;">odd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- ..-1 every other </span>
end for
<span style="color: #0000FF;">{</span><span style="color: #000000;">dx</span><span style="color: #0000FF;">,</span><span style="color: #000000;">dy</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">dy</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">dx</span><span style="color: #0000FF;">}</span> <span style="color: #000080;font-style:italic;">-- in new direction</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
for i=1 to n do
m[i] = join(m[i])
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)})</span>
end for
<!--</syntaxhighlight>-->
puts(1,join(m,"\n"))</lang>
{{out}}
<pre>
Line 3,652 ⟶ 3,965:
=={{header|PicoLisp}}==
This example uses 'grid' from "lib/simul.l", which maintains a two-dimensional structure and is normally used for simulations and board games.
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/simul.l")
 
(de spiral (N)
Line 3,670 ⟶ 3,983:
(for This L (prin (align 3 (: val))))
(prinl) )
(spiral 5) )</langsyntaxhighlight>
{{out}}
<pre> 1 2 3 4 5
Line 3,679 ⟶ 3,992:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">/* Generates a square matrix containing the integers from 0 to N**2-1, */
/* where N is the length of one side of the square. */
/* Written 22 February 2010. */
Line 3,733 ⟶ 4,046:
end;
 
end;</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">function Spiral-Matrix ( [int]$N )
{
# Initialize variables
Line 3,771 ⟶ 4,084:
Spiral-Matrix 5
""
Spiral-Matrix 7</langsyntaxhighlight>
{{out}}
<pre>1 2 3 4 5
Line 3,788 ⟶ 4,101:
 
=={{header|Prolog}}==
<syntaxhighlight lang="prolog">
<lang Prolog>
% Prolog implementation: SWI-Prolog 7.2.3
 
Line 3,840 ⟶ 4,153:
Sq is N*N-1, numlist(0, Sq, Ns),
create(N, EMx), spiralH(right, EMx, (0,0), Ns, Mx).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,854 ⟶ 4,167:
=={{header|PureBasic}}==
{{trans|Fortran}}
<langsyntaxhighlight PureBasiclang="purebasic">Procedure spiralMatrix(size = 1)
Protected i, x = -1, y, count = size, n
Dim a(size - 1,size - 1)
Line 3,910 ⟶ 4,223:
Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre>Spiral: 2
Line 3,927 ⟶ 4,240:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">def spiral(n):
dx,dy = 1,0 # Starting increments
x,y = 0,0 # Starting location
Line 3,948 ⟶ 4,261:
print
 
printspiral(spiral(5))</langsyntaxhighlight>
{{out}}
<pre>
Line 3,959 ⟶ 4,272:
 
===Recursive Solution===
<langsyntaxhighlight lang="python">def spiral(n):
def spiral_part(x, y, n):
if x == -1 and y == 0:
Line 3,981 ⟶ 4,294:
 
for row in spiral(5):
print " ".join("%2s" % x for x in row)</langsyntaxhighlight>
Adding a cache for the ''spiral_part'' function it could be quite efficient.
 
 
Recursion by rotating the solution for rest of the square except the first row,
<langsyntaxhighlight lang="python">def rot_right(a):
return zip(*a[::-1])
 
Line 4,003 ⟶ 4,316:
 
for row in spiral(5):
print(''.join('%3i' % i for i in row))</langsyntaxhighlight>
 
 
Another way, based on preparing lists ahead
<langsyntaxhighlight lang="python">def spiral(n):
dat = [[None] * n for i in range(n)]
le = [[i + 1, i + 1] for i in reversed(range(n))]
Line 4,022 ⟶ 4,335:
 
for row in spiral(5): # calc spiral and print it
print ' '.join('%3s' % x for x in row)</langsyntaxhighlight>
 
===Functional Solutions===
{{works with|Python|2.6, 3.0}}
<langsyntaxhighlight lang="python">import itertools
 
concat = itertools.chain.from_iterable
Line 4,044 ⟶ 4,357:
 
for row in spiral(5):
print(' '.join('%3s' % x for x in row))</langsyntaxhighlight>
 
 
Line 4,050 ⟶ 4,363:
{{Works with|Python|3.7}}
{{Trans|Haskell}}
<langsyntaxhighlight lang="python">'''Spiral Matrix'''
 
 
Line 4,093 ⟶ 4,406:
if __name__ == '__main__':
main()
</syntaxhighlight>
</lang>
{| class="wikitable" style="width:12em;height:12em;table-layout:fixed;"|-
| 0 || 1 || 2 || 3 || 4
Line 4,107 ⟶ 4,420:
 
=== Simple solution ===
<langsyntaxhighlight lang="python">def spiral_matrix(n):
m = [[0] * n for i in range(n)]
dx, dy = [0, 1, 0, -1], [1, 0, -1, 0]
Line 4,118 ⟶ 4,431:
c += 1
return m
for i in spiral_matrix(5): print(*i)</langsyntaxhighlight>
{{out}}
<syntaxhighlight lang="text">1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9</langsyntaxhighlight>
 
=={{header|Quackery}}==
Line 4,130 ⟶ 4,443:
This task really lends itself to a turtle graphics metaphor.
 
<langsyntaxhighlight Quackerylang="quackery"> [ stack ] is stepcount ( --> s )
[ stack ] is position ( --> s )
[ stack ] is heading ( --> s )
Line 4,176 ⟶ 4,489:
[ witheach
[ dup 10 < if sp echo sp ]
cr ]</langsyntaxhighlight>
 
{{out}}
Line 4,192 ⟶ 4,505:
=={{header|R}}==
===Sequence Solution===
<syntaxhighlight lang="rsplus">spiral <- function(n) matrix(order(cumsum(rep(rep_len(c(1, n, -1, -n), 2 * n - 1), n - seq(2 * n - 1) %/% 2))), n, byrow = T) - 1
<lang rsplus>spiral_matrix <- function(n) {
stopifnot(is.numeric(n))
stopifnot(n > 0)
steps <- c(1, n, -1, -n)
reps <- n - seq_len(n * 2 - 1L) %/% 2
indicies <- rep(rep_len(steps, length(reps)), reps)
indicies <- cumsum(indicies)
values <- integer(length(indicies))
values[indicies] <- seq_along(indicies)
matrix(values, n, n, byrow = TRUE)
}</lang>
{{out}}
<lang rsplus>> spiral_matrix(5)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 16 17 18 19 6
[3,] 15 24 25 20 7
[4,] 14 23 22 21 8
[5,] 13 12 11 10 9
 
spiral(5)</syntaxhighlight>
> t(spiral_matrix(5))
{{out}}
[,1] [,2] [,3] [,4] [,5]
[1,]<pre> [,1] [,2] [,3] 16 [,4] 15 14 13[,5]
[21,] 20 17 1 2 24 3 23 124
[32,] 15 3 16 18 17 25 18 22 115
[43,] 14 4 23 19 24 20 19 21 106
[54,] 13 5 22 6 21 720 8 9</lang>7
[5,] 12 11 10 9 8</pre>
 
===Recursive Solution===
<langsyntaxhighlight lang="rsplus">spiral_matrix <- function(n) {
spiralv <- function(v) {
n <- sqrt(length(v))
Line 4,235 ⟶ 4,531:
}
spiralv(1:(n^2))
}</langsyntaxhighlight>
 
===Iterative Solution===
Not the most elegant, but certainly distinct from the other R solutions. The key is the observation that we need to produce n elements from left to right, then n-1 elements down, then n-1 left, then n-2 right, then n-2 down, ... . This gives us two patterns. One in the direction that we need to write and another in the number of elements to write. After this, all that is left is battling R's indexing system.
<langsyntaxhighlight lang="rsplus">spiralMatrix <- function(n)
{
spiral <- matrix(0, nrow = n, ncol = n)
Line 4,265 ⟶ 4,561:
}
spiral
}</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require math)
Line 4,293 ⟶ 4,589:
 
(vector->matrix 4 4 (spiral 4 4))
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="racket">
(mutable-array #[#[0 1 2 3] #[11 12 13 4] #[10 15 14 5] #[9 8 7 6]])
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 4,303 ⟶ 4,599:
===Object-oriented Solution===
Suppose we set up a Turtle class like this:
<syntaxhighlight lang="raku" perl6line>class Turtle {
my @dv = [0,-1], [1,-1], [1,0], [1,1], [0,1], [-1,1], [-1,0], [-1,-1];
my $points = 8; # 'compass' points of neighbors on grid: north=0, northeast=1, east=2, etc.
Line 4,361 ⟶ 4,657:
}
$t.showmap;
}</langsyntaxhighlight>
 
Or we can build the spiral from inside-out like this:
 
<syntaxhighlight lang="raku" perl6line>sub MAIN(Int $size = 5) {
my $t = Turtle.new(dir => ($size %% 2 ?? 4 !! 0));
my $counter = $size * $size;
Line 4,375 ⟶ 4,671:
}
$t.showmap;
}</langsyntaxhighlight>
Note that with these "turtle graphics" we don't actually have to care about the coordinate system, since the <code>showmap</code> method can show whatever rectangle was modified by the turtle. So unlike the standard inside-out algorithm, we don't have to find the center of the matrix first.
 
===Procedural Solution===
<syntaxhighlight lang="raku" perl6line>sub spiral_matrix ( $n ) {
my @sm;
my $len = $n;
Line 4,397 ⟶ 4,693:
}
 
say .fmt('%3d') for spiral_matrix(5);</langsyntaxhighlight>
{{out}}
<pre> 0 1 2 3 4
Line 4,408 ⟶ 4,704:
Original logic borrowed (mostly) from the [[#Fortran|Fortran]] example.
===static column width===
<langsyntaxhighlight lang="rexx">/*REXX program displays a spiral in a square array (of any size) starting at START. */
parse arg size start . /*obtain optional arguments from the CL*/
if size =='' | size =="," then size =5 /*Not specified? Then use the default.*/
Line 4,429 ⟶ 4,725:
end /*col*/ /* [↑] line has an extra leading blank*/
say _ /*display a line (row) of the spiral. */
end /*row*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; using the default array size of: &nbsp; '''5'''}}
<pre>
Line 4,495 ⟶ 4,791:
===minimum column width===
This REXX version automatically adjusts the width of the spiral matrix columns to minimize the area of the matrix display (so more elements may be shown on a display screen).
<langsyntaxhighlight lang="rexx">/*REXX program displays a spiral in a square array (of any size) starting at START. */
parse arg size start . /*obtain optional arguments from the CL*/
if size =='' | size =="," then size =5 /*Not specified? Then use the default.*/
Line 4,520 ⟶ 4,816:
if two then say substr(_, 2) /*this SUBSTR ignores the first blank. */
end /*r*/
end /*two*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; (shown at <sup>3</sup>/<sub>4</sub> size) &nbsp; using an array size of: &nbsp; '''36'''
<b>
Line 4,564 ⟶ 4,860:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Spiral matrix
 
Line 4,618 ⟶ 4,914:
exec()
}
</syntaxhighlight>
</lang>
Output:
 
[http://kepkezelokeptarhely.comeu/images/qyooy2wqd8s502ul977vview.php?file=20220218v00xuh6r2.jpgjpeg Spiral matrix]
 
=={{header|RPL}}==
{{works with|RPL|HP48-R}}
« { 0 1 } → n step
« { 1 1 } n DUP 2 →LIST -1 CON <span style="color:grey">@ empty cell = -1</span>
1 n SQ '''FOR''' j
OVER j PUT
DUP2 SWAP step ADD
'''IF IFERR''' GET '''THEN''' DROP2 1 '''ELSE''' -1 ≠ '''END''' <span style="color:grey">@ if next step is out of border or an already written cell</span>
'''THEN''' step REVLIST { 1 -1 } * 'step' STO '''END''' <span style="color:grey">@ then turn right</span>
SWAP step ADD SWAP
'''NEXT'''
» » '<span style="color:blue">SPIRAL</span>' STO
 
5 <span style="color:blue">SPIRAL</span>
{{out}}
<pre>
1: [[1 2 3 4 5]
[16 17 18 19 6]
[15 24 25 20 7]
[14 23 22 21 8]
[13 12 11 10 9]]
</pre>
 
=={{header|Ruby}}==
{{trans|Python}}
<langsyntaxhighlight lang="ruby">def spiral(n)
spiral = Array.new(n) {Array.new(n, nil)} # n x n array of nils
runs = n.downto(0).each_cons(2).to_a.flatten # n==5; [5,4,4,3,3,2,2,1,1,0]
Line 4,642 ⟶ 4,961:
end
 
print_matrix spiral(5)</langsyntaxhighlight>
{{out}}
<pre>
Line 4,654 ⟶ 4,973:
The other way
{{trans|D}}
<langsyntaxhighlight lang="ruby">n = 5
m = Array.new(n){Array.new(n)}
pos, side = -1, n
Line 4,666 ⟶ 4,985:
 
fmt = "%#{(n*n-1).to_s.size}d " * n
puts m.map{|row| fmt % row}</langsyntaxhighlight>
 
Output as above.
Line 4,672 ⟶ 4,991:
 
It processes the Array which is for work without creating it.
<langsyntaxhighlight lang="ruby">def spiral_matrix(n)
x, y, dx, dy = -1, 0, 0, -1
fmt = "%#{(n*n-1).to_s.size}d " * n
Line 4,681 ⟶ 5,000:
end
 
spiral_matrix(5)</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">const VECTORS: [(isize, isize); 4] = [(1, 0), (0, 1), (-1, 0), (0, -1)];
 
pub fn spiral_matrix(size: usize) -> Vec<Vec<u32>> {
Line 4,710 ⟶ 5,029:
println!();
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,721 ⟶ 5,040:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">class Folder(){
var dir = (1,0)
var pos = (-1,0)
Line 4,742 ⟶ 5,061:
folds.foreach {len => fold(seq.take(len),array); seq = seq.drop(len)}
array
}</langsyntaxhighlight>
Explanation: if you see the sequence of numbers to spiral around as a tape to fold around, you can see this pattern on the lenght of tape segment to fold in each step:
:<math>N,\ N-1,\ N-1,\ \ldots,\ 1,\ 1</math>
Line 4,754 ⟶ 5,073:
=={{header|Scilab}}==
{{trans|Octave}}
<syntaxhighlight lang="text">function a = spiral(n)
a = ones(n*n, 1)
v = ones(n, 1)
Line 4,778 ⟶ 5,097:
14. 23. 24. 19. 6.
13. 22. 21. 20. 7.
12. 11. 10. 9. 8.</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const type: matrix is array array integer;
Line 4,832 ⟶ 5,151:
begin
writeMatrix(spiral(5));
end func;</langsyntaxhighlight>
{{out}}
<pre>
Line 4,844 ⟶ 5,163:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func spiral(n) {
var (x, y, dx, dy, a) = (0, 0, 1, 0, [])
{ |i|
Line 4,863 ⟶ 5,182:
spiral(5).each { |row|
row.map {"%3d" % _}.join(' ').say
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,874 ⟶ 5,193:
 
=={{header|Stata}}==
<langsyntaxhighlight lang="stata">function spiral_mat(n) {
a = J(n*n, 1, 1)
u = J(n, 1, -n)
Line 4,894 ⟶ 5,213:
4 | 13 22 21 20 7 |
5 | 12 11 10 9 8 |
+--------------------------+</langsyntaxhighlight>
 
=={{header|Tcl}}==
Using <code>print_matrix</code> from [[Matrix Transpose#Tcl]]
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
namespace path {::tcl::mathop}
proc spiral size {
Line 4,931 ⟶ 5,250:
}
 
print_matrix [spiral 5]</langsyntaxhighlight>
<pre> 0 1 2 3 4
15 16 17 18 5
Line 4,940 ⟶ 5,259:
=={{header|TI-83 BASIC}}==
{{trans|BBC Basic}}
<langsyntaxhighlight lang="ti83b">5->N
DelVar [F]
{N,N}→dim([F])
Line 4,979 ⟶ 5,298:
G→E
End
[F]</langsyntaxhighlight>
{{out}}
<pre>[[0 1 2 3 4]
Line 4,988 ⟶ 5,307:
 
=={{header|TSE SAL}}==
<syntaxhighlight lang="tse sal">
<lang TSE SAL>
 
// library: math: create: array: spiral: inwards <description></description> <version control></version control> <version>1.0.0.0.15</version> (filenamemacro=creamasi.s) [<Program>] [<Research>] [kn, ri, mo, 31-12-2012 01:15:43]
Line 5,117 ⟶ 5,436:
END
 
</syntaxhighlight>
</lang>
 
=={{header|uBasic/4tH}}==
{{trans|C}}
This recursive version is quite compact.
<syntaxhighlight lang="text">Input "Width: ";w
Input "Height: ";h
Print
Line 5,140 ⟶ 5,459:
Else
Return (c@)
EndIf</langsyntaxhighlight>
 
=={{header|Ursala}}==
Helpful hints from the [[#J|J]] example are gratefully acknowledged. The spiral function works for any n, and results are shown for n equal to 5, 6, and 7. The results are represented as lists of lists rather than arrays.
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
#import int
Line 5,156 ⟶ 5,475:
#cast %nLLL
 
examples = spiral* <5,6,7></langsyntaxhighlight>
{{out}}
<pre>
Line 5,184 ⟶ 5,503:
=={{header|VBScript}}==
{{trans|BBC BASIC}}
<syntaxhighlight lang="vb">
<lang vb>
Function build_spiral(n)
botcol = 0 : topcol = n - 1
Line 5,232 ⟶ 5,551:
 
build_spiral(CInt(WScript.Arguments(0)))
</syntaxhighlight>
</lang>
 
{{Out}}
Line 5,257 ⟶ 5,576:
{{trans|Java}}
This requires VB6.
<langsyntaxhighlight lang="vb">Option Explicit
 
Sub Main()
Line 5,314 ⟶ 5,633:
Debug.Print arr(row, UBound(arr, 2))
Next
End Sub</langsyntaxhighlight>
 
==={{header|VBA}}===
Line 5,320 ⟶ 5,639:
{{trans|Java}}
{{works with|VBA/Excel}}
<langsyntaxhighlight lang="vb">Sub spiral()
Dim n As Integer, a As Integer, b As Integer
Dim numCsquares As Integer, sideLen As Integer, currNum As Integer
Line 5,370 ⟶ 5,689:
Next b
Next a
End Sub</langsyntaxhighlight>
 
====Solution 2====
<langsyntaxhighlight lang="vb">Sub spiral(n As Integer)
Const FREE = -9 'negative number indicates unoccupied cell
Dim A() As Integer
Line 5,440 ⟶ 5,759:
Next
End Sub</langsyntaxhighlight>
{{out}}
<pre>
Line 5,462 ⟶ 5,781:
'''Platform:''' [[.NET]]<br>
From VB6. This requires Visual Basic .Net.
<langsyntaxhighlight lang="vbnet">Module modSpiralArray
Sub Main()
print2dArray(getSpiralArray(5))
Line 5,517 ⟶ 5,836:
 
End Module
</syntaxhighlight>
</lang>
 
=={{header|Wren}}==
{{trans|Go}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Conv, Fmt
 
var n = 5
Line 5,577 ⟶ 5,896:
if (i%n == n - 1) System.print()
i = i + 1
}</langsyntaxhighlight>
 
{{out}}
Line 5,589 ⟶ 5,908:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">def N=5;
int A(N,N);
int I, J, X, Y, Steps, Dir;
Line 5,610 ⟶ 5,929:
until Steps = 0;
Cursor(0,N);
]</langsyntaxhighlight>
 
{{out}}
Line 5,619 ⟶ 5,938:
13 22 21 20 7
12 11 10 9 8
</pre>
 
=={{header|Z80 Assembly}}==
N is set at beginning of code (valid range 1..150-ish, then you soon run out of memory), sjasmplus syntax, CP/M executable:
<syntaxhighlight lang="z80">; Spiral matrix in Z80 assembly (for CP/M OS - you can use `tnylpo` or `z88dk-ticks` on PC)
OPT --syntax=abf : OUTPUT "spiralmt.com" ; asm syntax for z00m's variant of sjasmplus
ORG $100
spiral_matrix:
ld a,5 ; N matrix size (argument for the code) (valid range: 1..150)
; setup phase
push af
ld l,a
ld h,0
add hl,hl
ld (delta_d),hl ; down-direction address delta = +N*2
neg
ld l,a
ld h,$FF
add hl,hl
ld (delta_u),hl ; up-direction address delta = -N*2
neg
ld hl,matrix
ld de,2 ; delta_r value to move right in matrix
ld bc,0 ; starting value
dec a ; first sequences will be N-1 long
jr z,.finish ; 1x1 doesn't need any sequence, just set last element
call set_sequence ; initial entry sequence has N-1 elements (same as two more)
; main loop - do twice same length sequence, then decrement length, until zero
.loop:
call set_sequence_twice
dec a
jr nz,.loop
.finish: ; whole spiral is set except last element, set it now
ld (hl),c
inc hl
ld (hl),b
; print matrix - reading it by POP HL (destructive, plus some memory ahead of matrix too)
pop de ; d = N
ld (.oldsp+1),sp
ld sp,matrix ; set stack to beginning of matrix (call/push does damage memory ahead)
ld c,d ; c = N (lines counter)
.print_rows:
ld b,d ; b = N (value per row counter)
.print_row:
pop hl
push de
push bc
call print_hl
pop bc
pop de
djnz .print_row
push de
call print_crlf
pop de
dec c
jr nz,.print_rows
.oldsp:
ld sp,0
rst 0 ; return to CP/M
 
print_crlf:
ld e,10
call print_char
ld e,13
jr print_char
print_hl:
ld b,' '
ld e,b
call print_char
ld de,-10000
call extract_digit
ld de,-1000
call extract_digit
ld de,-100
call extract_digit
ld de,-10
call extract_digit
ld a,l
print_digit:
ld b,'0'
add a,b
ld e,a
print_char:
push bc
push hl
ld c,2
call 5
pop hl
pop bc
ret
extract_digit:
ld a,-1
.digit_loop:
inc a
add hl,de
jr c,.digit_loop
sbc hl,de
or a
jr nz,print_digit
ld e,b
jr print_char
 
set_sequence_twice:
call set_sequence
set_sequence:
; A = length, HL = next_to_matrix, DE = delta to advance hl, BC = next_value
push af
.set_loop:
ld (hl),c
inc hl
ld (hl),b
dec hl ; [HL] = BC
add hl,de ; HL += DE
inc bc ; ++BC
dec a
jr nz,.set_loop
push hl ; change DE for next direction (right->down->left->up->right->...)
.d: ld hl,delta_d ; self-modify-code: pointer to next delta
ld e,(hl)
inc hl
ld d,(hl) ; de = address delta for next sequence
inc hl
ld a,low delta_u+2 ; if hl == delta_u+2 => reset it back to delta_r
cp l
jr nz,.next_delta
ld hl,delta_r
.next_delta:
ld (.d+1),hl ; self modify code pointer for next delta value
pop hl
pop af
ret
 
delta_r: dw +2 ; value to add to move right in matrix
delta_d: dw 0 ; value to add to move down in matrix (set to +N*2)
delta_l: dw -2 ; value to add to move left in matrix
delta_u: dw 0 ; value to add to move up in matrix (set to -N*2)
 
matrix:
; following memory is used for NxN matrix of uint16_t values (150x150 needs 45000 bytes)</syntaxhighlight>
 
{{out}}
<pre>
$ tnylpo spiralmt.com
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8
</pre>
 
=={{header|zkl}}==
{{trans|C}} which turns out to be the same as Ruby
<langsyntaxhighlight lang="zkl">fcn spiralMatrix(n){
sm:=(0).pump(n,List,(0).pump(n,List,False).copy); //L(L(False,False..), L(F,F,..) ...)
drc:=Walker.cycle(T(0,1,0), T(1,0,1), T(0,-1,0), T(-1,0,1)); // deltas
Line 5,631 ⟶ 6,098:
}
sm
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">foreach n in (T(5,-1,0,1,2)){
spiralMatrix(n).pump(Console.println,fcn(r){ r.apply("%4d".fmt).concat() });
println("---");
}</langsyntaxhighlight>
{{out}}
<pre>
1,150

edits