Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
3
Task/Spiral-matrix/00-META.yaml
Normal file
3
Task/Spiral-matrix/00-META.yaml
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
---
|
||||
from: http://rosettacode.org/wiki/Spiral_matrix
|
||||
note: Matrices
|
||||
24
Task/Spiral-matrix/00-TASK.txt
Normal file
24
Task/Spiral-matrix/00-TASK.txt
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
;Task:
|
||||
Produce a spiral array.
|
||||
|
||||
|
||||
A ''spiral array'' is a square arrangement of the first <big> N<sup>2</sup></big> natural numbers, where the
|
||||
<br>numbers increase sequentially as you go around the edges of the array spiraling inwards.
|
||||
|
||||
|
||||
For example, given '''5''', produce this array:
|
||||
<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>
|
||||
|
||||
|
||||
;Related tasks:
|
||||
* [[Zig-zag matrix]]
|
||||
* [[Identity_matrix]]
|
||||
* [[Ulam_spiral_(for_primes)]]
|
||||
<br><br>
|
||||
|
||||
19
Task/Spiral-matrix/11l/spiral-matrix.11l
Normal file
19
Task/Spiral-matrix/11l/spiral-matrix.11l
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
F spiral_matrix(n)
|
||||
V m = [[0] * n] *n
|
||||
V d = [(0, 1), (1, 0), (0, -1), (-1, 0)]
|
||||
V xy = (0, -1)
|
||||
V c = 0
|
||||
L(i) 0 .< n + n - 1
|
||||
L 0 .< (n + n - i) I/ 2
|
||||
xy += d[i % 4]
|
||||
m[xy.x][xy.y] = c
|
||||
c++
|
||||
R m
|
||||
|
||||
F printspiral(myarray)
|
||||
L(y) 0 .< myarray.len
|
||||
L(x) 0 .< myarray.len
|
||||
print(‘#2’.format(myarray[y][x]), end' ‘ ’)
|
||||
print()
|
||||
|
||||
printspiral(spiral_matrix(5))
|
||||
120
Task/Spiral-matrix/360-Assembly/spiral-matrix.360
Normal file
120
Task/Spiral-matrix/360-Assembly/spiral-matrix.360
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
SPIRALM CSECT
|
||||
USING SPIRALM,R13
|
||||
SAVEAREA B STM-SAVEAREA(R15)
|
||||
DC 17F'0'
|
||||
DC CL8'SPIRALM'
|
||||
STM STM R14,R12,12(R13)
|
||||
ST R13,4(R15)
|
||||
ST R15,8(R13)
|
||||
LR R13,R15
|
||||
* ---- CODE
|
||||
LA R0,0
|
||||
LA R1,1
|
||||
LH R12,N n
|
||||
LR R4,R1 Row=1
|
||||
LR R5,R1 Col=1
|
||||
LR R6,R1 BotRow=1
|
||||
LR R7,R1 BotCol=1
|
||||
LR R8,R12 TopRow=n
|
||||
LR R9,R12 TopCol=n
|
||||
LR R10,R0 Dir=0
|
||||
LR R15,R12 n
|
||||
MR R14,R12 R15=n*n
|
||||
LA R11,1 k=1
|
||||
LOOP CR R11,R15
|
||||
BH ENDLOOP
|
||||
LR R1,R4
|
||||
BCTR R1,0
|
||||
MH R1,N
|
||||
AR R1,R5
|
||||
LR R2,R11 k
|
||||
BCTR R2,0
|
||||
BCTR R1,0
|
||||
SLA R1,1
|
||||
STH R2,MATRIX(R1) Matrix(Row,Col)=k-1
|
||||
CH R10,=H'0'
|
||||
BE DIR0
|
||||
CH R10,=H'1'
|
||||
BE DIR1
|
||||
CH R10,=H'2'
|
||||
BE DIR2
|
||||
CH R10,=H'3'
|
||||
BE DIR3
|
||||
B DIRX
|
||||
DIR0 CR R5,R9 if Col<TopCol
|
||||
BNL DIR0S
|
||||
LA R5,1(R5) Col=Col+1
|
||||
B DIRX
|
||||
DIR0S LA R10,1 Dir=1
|
||||
LA R4,1(R4) Row=Row+1
|
||||
LA R6,1(R6) BotRow=BotRow+1
|
||||
B DIRX
|
||||
DIR1 CR R4,R8 if Row<TopRow
|
||||
BNL DIR1S
|
||||
LA R4,1(R4) Row=Row+1
|
||||
B DIRX
|
||||
DIR1S LA R10,2 Dir=2
|
||||
BCTR R5,0 Col=Col-1
|
||||
BCTR R9,0 TopCol=TopCol-1
|
||||
B DIRX
|
||||
DIR2 CR R5,R7 if Col>BotCol
|
||||
BNH DIR2S
|
||||
BCTR R5,0 Col=Col-1
|
||||
B DIRX
|
||||
DIR2S LA R10,3 Dir=3
|
||||
BCTR R4,0 Row=Row-1
|
||||
BCTR R8,0 TopRow=TopRow-1
|
||||
B DIRX
|
||||
DIR3 CR R4,R6 if Row>BotRow
|
||||
BNH DIR3S
|
||||
BCTR R4,0 Row=Row-1
|
||||
B DIRX
|
||||
DIR3S LA R10,0 Dir=0
|
||||
LA R5,1(R5) Col=Col+1
|
||||
LA R7,1(R7) BotCol=BotCol+1
|
||||
DIRX EQU *
|
||||
LA R11,1(R11) k=k+1
|
||||
B LOOP
|
||||
ENDLOOP EQU *
|
||||
LA R4,1 i
|
||||
LOOPI CR R4,R12
|
||||
BH ENDLOOPI
|
||||
XR R10,R10
|
||||
LA R5,1 j
|
||||
LOOPJ CR R5,R12
|
||||
BH ENDLOOPJ
|
||||
LR R1,R4
|
||||
BCTR R1,0
|
||||
MH R1,N
|
||||
AR R1,R5
|
||||
BCTR R1,0
|
||||
SLA R1,1
|
||||
LH R2,MATRIX(R1) Matrix(i,j)
|
||||
LA R3,BUF
|
||||
AR R3,R10
|
||||
CVD R2,P8
|
||||
MVC 0(4,R3),=X'40202120'
|
||||
ED 0(4,R3),P8+6
|
||||
LA R10,4(R10)
|
||||
LA R5,1(R5)
|
||||
B LOOPJ
|
||||
ENDLOOPJ EQU *
|
||||
WTO MF=(E,WTOMSG)
|
||||
LA R4,1(R4)
|
||||
B LOOPI
|
||||
ENDLOOPI EQU *
|
||||
* ---- END CODE
|
||||
L R13,4(0,R13)
|
||||
LM R14,R12,12(R13)
|
||||
XR R15,R15
|
||||
BR R14
|
||||
* ---- DATA
|
||||
N DC H'5' max=20 (20*4=80)
|
||||
LTORG
|
||||
P8 DS PL8
|
||||
WTOMSG DS 0F
|
||||
DC H'80',XL2'0000'
|
||||
BUF DC CL80' '
|
||||
MATRIX DS H Matrix(n,n)
|
||||
YREGS
|
||||
END SPIRALM
|
||||
121
Task/Spiral-matrix/ABAP/spiral-matrix.abap
Normal file
121
Task/Spiral-matrix/ABAP/spiral-matrix.abap
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
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( ).
|
||||
34
Task/Spiral-matrix/ALGOL-68/spiral-matrix.alg
Normal file
34
Task/Spiral-matrix/ALGOL-68/spiral-matrix.alg
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
INT empty=0;
|
||||
|
||||
PROC spiral = (INT n)[,]INT: (
|
||||
INT dx:=1, dy:=0; # Starting increments #
|
||||
INT x:=0, y:=0; # Starting location #
|
||||
[0:n-1,0:n-1]INT my array;
|
||||
FOR y FROM LWB my array TO UPB my array DO
|
||||
FOR x FROM LWB my array TO UPB my array DO
|
||||
my array[x,y]:=empty
|
||||
OD
|
||||
OD;
|
||||
FOR i TO n**2 DO
|
||||
my array[x,y] := i;
|
||||
INT nx:=x+dx, ny:=y+dy;
|
||||
IF ( 0<=nx AND nx<n AND 0<=ny AND ny<n | my array[nx,ny] = empty | FALSE ) THEN
|
||||
x:=nx; y:=ny
|
||||
ELSE
|
||||
INT swap:=dx; dx:=-dy; dy:=swap;
|
||||
x+:=dx; y+:=dy
|
||||
FI
|
||||
OD;
|
||||
my array
|
||||
);
|
||||
|
||||
PROC print spiral = ([,]INT my array)VOID:(
|
||||
FOR y FROM LWB my array TO UPB my array DO
|
||||
FOR x FROM LWB my array TO UPB my array DO
|
||||
print(whole(my array[x,y],-3))
|
||||
OD;
|
||||
print(new line)
|
||||
OD
|
||||
);
|
||||
|
||||
print spiral(spiral(5))
|
||||
39
Task/Spiral-matrix/AWK/spiral-matrix.awk
Normal file
39
Task/Spiral-matrix/AWK/spiral-matrix.awk
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
# syntax: GAWK -f SPIRAL_MATRIX.AWK [-v offset={0|1}] [size]
|
||||
# converted from BBC BASIC
|
||||
BEGIN {
|
||||
# offset: "0" prints 0 to size^2-1 while "1" prints 1 to size^2
|
||||
offset = (offset == "") ? 0 : offset
|
||||
size = (ARGV[1] == "") ? 5 : ARGV[1]
|
||||
if (offset !~ /^[01]$/) { exit(1) }
|
||||
if (size !~ /^[0-9]+$/) { exit(1) }
|
||||
bot_col = bot_row = 0
|
||||
top_col = top_row = size - 1
|
||||
direction = col = row = 0
|
||||
for (i=0; i<=size*size-1; i++) { # build
|
||||
arr[col,row] = i + offset
|
||||
if (direction == 0) {
|
||||
if (col < top_col) { col++ }
|
||||
else { direction = 1 ; row++ ; bot_row++ }
|
||||
}
|
||||
else if (direction == 1) {
|
||||
if (row < top_row) { row++ }
|
||||
else { direction = 2 ; col-- ; top_col-- }
|
||||
}
|
||||
else if (direction == 2) {
|
||||
if (col > bot_col) { col-- }
|
||||
else { direction = 3 ; row-- ; top_row-- }
|
||||
}
|
||||
else if (direction == 3) {
|
||||
if (row > bot_row) { row-- }
|
||||
else { direction = 0 ; col++ ; bot_col++ }
|
||||
}
|
||||
}
|
||||
width = length(size ^ 2 - 1 + offset) + 1 # column width
|
||||
for (i=0; i<size; i++) { # print
|
||||
for (j=0; j<size; j++) {
|
||||
printf("%*d",width,arr[j,i])
|
||||
}
|
||||
printf("\n")
|
||||
}
|
||||
exit(0)
|
||||
}
|
||||
69
Task/Spiral-matrix/Action-/spiral-matrix.action
Normal file
69
Task/Spiral-matrix/Action-/spiral-matrix.action
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
DEFINE MAX_SIZE="10"
|
||||
DEFINE MAX_MATRIX_SIZE="100"
|
||||
|
||||
INT FUNC Index(BYTE size,x,y)
|
||||
RETURN (x+y*size)
|
||||
|
||||
PROC PrintMatrix(BYTE ARRAY a BYTE size)
|
||||
BYTE i,j,v
|
||||
|
||||
FOR j=0 TO size-1
|
||||
DO
|
||||
FOR i=0 TO size-1
|
||||
DO
|
||||
v=a(Index(size,i,j))
|
||||
IF v<10 THEN
|
||||
Print(" ")
|
||||
ELSE
|
||||
Print(" ")
|
||||
FI
|
||||
PrintB(v)
|
||||
OD
|
||||
PutE()
|
||||
OD
|
||||
RETURN
|
||||
|
||||
PROC FillMatrix(BYTE ARRAY a BYTE size)
|
||||
INT lev,maxLev,dist,maxDist,v
|
||||
|
||||
maxLev=size/2
|
||||
IF (size&1)=0 THEN
|
||||
maxLev==-1
|
||||
FI
|
||||
maxDist=size-1
|
||||
v=1
|
||||
FOR lev=0 TO maxLev
|
||||
DO
|
||||
FOR dist=0 TO maxDist
|
||||
DO
|
||||
a(Index(size,lev+dist,lev))=v v==+1
|
||||
OD
|
||||
FOR dist=0 TO maxDist-1
|
||||
DO
|
||||
a(Index(size,size-1-lev,lev+dist+1))=v v==+1
|
||||
OD
|
||||
FOR dist=0 TO maxDist-1
|
||||
DO
|
||||
a(Index(size,size-2-lev-dist,size-1-lev))=v v==+1
|
||||
OD
|
||||
FOR dist=0 TO maxDist-2
|
||||
DO
|
||||
a(Index(size,lev,size-2-lev-dist))=v v==+1
|
||||
OD
|
||||
maxDist==-2
|
||||
OD
|
||||
RETURN
|
||||
|
||||
PROC Test(BYTE size)
|
||||
BYTE ARRAY mat(MAX_MATRIX_SIZE)
|
||||
|
||||
PrintF("Matrix size: %B%E",size)
|
||||
FillMatrix(mat,size)
|
||||
PrintMatrix(mat,size)
|
||||
PutE()
|
||||
RETURN
|
||||
|
||||
PROC Main()
|
||||
Test(5)
|
||||
Test(6)
|
||||
RETURN
|
||||
67
Task/Spiral-matrix/Ada/spiral-matrix-1.ada
Normal file
67
Task/Spiral-matrix/Ada/spiral-matrix-1.ada
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
-- Spiral Square
|
||||
with Ada.Text_Io; use Ada.Text_Io;
|
||||
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
|
||||
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
|
||||
|
||||
procedure Spiral_Square is
|
||||
type Array_Type is array(Positive range <>, Positive range <>) of Natural;
|
||||
|
||||
function Spiral (N : Positive) return Array_Type is
|
||||
Result : Array_Type(1..N, 1..N);
|
||||
Row : Natural := 1;
|
||||
Col : Natural := 1;
|
||||
Max_Row : Natural := N;
|
||||
Max_Col : Natural := N;
|
||||
Min_Row : Natural := 1;
|
||||
Min_Col : Natural := 1;
|
||||
begin
|
||||
for I in 0..N**2 - 1 loop
|
||||
Result(Row, Col) := I;
|
||||
if Row = Min_Row then
|
||||
Col := Col + 1;
|
||||
if Col > Max_Col then
|
||||
Col := Max_Col;
|
||||
Row := Row + 1;
|
||||
end if;
|
||||
elsif Col = Max_Col then
|
||||
Row := Row + 1;
|
||||
if Row > Max_Row then
|
||||
Row := Max_Row;
|
||||
Col := Col - 1;
|
||||
end if;
|
||||
elsif Row = Max_Row then
|
||||
Col := Col - 1;
|
||||
if Col < Min_Col then
|
||||
Col := Min_Col;
|
||||
Row := Row - 1;
|
||||
end if;
|
||||
elsif Col = Min_Col then
|
||||
Row := Row - 1;
|
||||
if Row = Min_Row then -- Reduce spiral
|
||||
Min_Row := Min_Row + 1;
|
||||
Max_Row := Max_Row - 1;
|
||||
Row := Min_Row;
|
||||
Min_Col := Min_Col + 1;
|
||||
Max_Col := Max_Col - 1;
|
||||
Col := Min_Col;
|
||||
end if;
|
||||
end if;
|
||||
end loop;
|
||||
return Result;
|
||||
end Spiral;
|
||||
|
||||
procedure Print(Item : Array_Type) is
|
||||
Num_Digits : constant Float := Log(X => Float(Item'Length(1)**2), Base => 10.0);
|
||||
Spacing : constant Positive := Integer(Num_Digits) + 2;
|
||||
begin
|
||||
for I in Item'range(1) loop
|
||||
for J in Item'range(2) loop
|
||||
Put(Item => Item(I,J), Width => Spacing);
|
||||
end loop;
|
||||
New_Line;
|
||||
end loop;
|
||||
end Print;
|
||||
|
||||
begin
|
||||
Print(Spiral(5));
|
||||
end Spiral_Square;
|
||||
33
Task/Spiral-matrix/Ada/spiral-matrix-2.ada
Normal file
33
Task/Spiral-matrix/Ada/spiral-matrix-2.ada
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
function Spiral (N : Positive) return Array_Type is
|
||||
Result : Array_Type (1..N, 1..N);
|
||||
Left : Positive := 1;
|
||||
Right : Positive := N;
|
||||
Top : Positive := 1;
|
||||
Bottom : Positive := N;
|
||||
Index : Natural := 0;
|
||||
begin
|
||||
while Left < Right loop
|
||||
for I in Left..Right - 1 loop
|
||||
Result (Top, I) := Index;
|
||||
Index := Index + 1;
|
||||
end loop;
|
||||
for J in Top..Bottom - 1 loop
|
||||
Result (J, Right) := Index;
|
||||
Index := Index + 1;
|
||||
end loop;
|
||||
for I in reverse Left + 1..Right loop
|
||||
Result (Bottom, I) := Index;
|
||||
Index := Index + 1;
|
||||
end loop;
|
||||
for J in reverse Top + 1..Bottom loop
|
||||
Result (J, Left) := Index;
|
||||
Index := Index + 1;
|
||||
end loop;
|
||||
Left := Left + 1;
|
||||
Right := Right - 1;
|
||||
Top := Top + 1;
|
||||
Bottom := Bottom - 1;
|
||||
end loop;
|
||||
Result (Top, Left) := Index;
|
||||
return Result;
|
||||
end Spiral;
|
||||
257
Task/Spiral-matrix/AppleScript/spiral-matrix.applescript
Normal file
257
Task/Spiral-matrix/AppleScript/spiral-matrix.applescript
Normal file
|
|
@ -0,0 +1,257 @@
|
|||
---------------------- SPIRAL MATRIX ---------------------
|
||||
|
||||
-- spiral :: Int -> [[Int]]
|
||||
on spiral(n)
|
||||
script go
|
||||
on |λ|(rows, cols, start)
|
||||
if 0 < rows then
|
||||
{enumFromTo(start, start + pred(cols))} & ¬
|
||||
map(my |reverse|, ¬
|
||||
transpose(|λ|(cols, pred(rows), start + cols)))
|
||||
else
|
||||
{{}}
|
||||
end if
|
||||
end |λ|
|
||||
end script
|
||||
|
||||
go's |λ|(n, n, 0)
|
||||
end spiral
|
||||
|
||||
|
||||
--------------------------- TEST -------------------------
|
||||
on run
|
||||
wikiTable(spiral(5), ¬
|
||||
false, ¬
|
||||
"text-align:center;width:12em;height:12em;table-layout:fixed;")
|
||||
end run
|
||||
|
||||
|
||||
-------------------- WIKI TABLE FORMAT -------------------
|
||||
|
||||
-- wikiTable :: [Text] -> Bool -> Text -> Text
|
||||
on wikiTable(lstRows, blnHdr, strStyle)
|
||||
script fWikiRows
|
||||
on |λ|(lstRow, iRow)
|
||||
set strDelim to if_(blnHdr and (iRow = 0), "!", "|")
|
||||
set strDbl to strDelim & strDelim
|
||||
linefeed & "|-" & linefeed & strDelim & space & ¬
|
||||
intercalateS(space & strDbl & space, lstRow)
|
||||
end |λ|
|
||||
end script
|
||||
|
||||
linefeed & "{| class=\"wikitable\" " & ¬
|
||||
if_(strStyle ≠ "", "style=\"" & strStyle & "\"", "") & ¬
|
||||
intercalateS("", ¬
|
||||
map(fWikiRows, lstRows)) & linefeed & "|}" & linefeed
|
||||
end wikiTable
|
||||
|
||||
|
||||
------------------------- GENERIC ------------------------
|
||||
|
||||
-- comparing :: (a -> b) -> (a -> a -> Ordering)
|
||||
on comparing(f)
|
||||
script
|
||||
on |λ|(a, b)
|
||||
tell mReturn(f)
|
||||
set fa to |λ|(a)
|
||||
set fb to |λ|(b)
|
||||
if fa < fb then
|
||||
-1
|
||||
else if fa > fb then
|
||||
1
|
||||
else
|
||||
0
|
||||
end if
|
||||
end tell
|
||||
end |λ|
|
||||
end script
|
||||
end comparing
|
||||
|
||||
|
||||
-- concatMap :: (a -> [b]) -> [a] -> [b]
|
||||
on concatMap(f, xs)
|
||||
set lng to length of xs
|
||||
set acc to {}
|
||||
tell mReturn(f)
|
||||
repeat with i from 1 to lng
|
||||
set acc to acc & (|λ|(item i of xs, i, xs))
|
||||
end repeat
|
||||
end tell
|
||||
if {text, string} contains class of xs then
|
||||
acc as text
|
||||
else
|
||||
acc
|
||||
end if
|
||||
end concatMap
|
||||
|
||||
|
||||
-- enumFromTo :: Int -> Int -> [Int]
|
||||
on enumFromTo(m, n)
|
||||
if m ≤ n then
|
||||
set lst to {}
|
||||
repeat with i from m to n
|
||||
set end of lst to i
|
||||
end repeat
|
||||
return lst
|
||||
else
|
||||
return {}
|
||||
end if
|
||||
end enumFromTo
|
||||
|
||||
|
||||
-- foldl :: (a -> b -> a) -> a -> [b] -> a
|
||||
on foldl(f, startValue, xs)
|
||||
tell mReturn(f)
|
||||
set v to startValue
|
||||
set lng to length of xs
|
||||
repeat with i from 1 to lng
|
||||
set v to |λ|(v, item i of xs, i, xs)
|
||||
end repeat
|
||||
return v
|
||||
end tell
|
||||
end foldl
|
||||
|
||||
|
||||
-- if_ :: Bool -> a -> a -> a
|
||||
on if_(bool, x, y)
|
||||
if bool then
|
||||
x
|
||||
else
|
||||
y
|
||||
end if
|
||||
end if_
|
||||
|
||||
|
||||
-- intercalateS :: String -> [String] -> String
|
||||
on intercalateS(sep, xs)
|
||||
set {dlm, my text item delimiters} to {my text item delimiters, sep}
|
||||
set s to xs as text
|
||||
set my text item delimiters to dlm
|
||||
return s
|
||||
end intercalateS
|
||||
|
||||
|
||||
-- length :: [a] -> Int
|
||||
on |length|(xs)
|
||||
length of xs
|
||||
end |length|
|
||||
|
||||
|
||||
-- max :: Ord a => a -> a -> a
|
||||
on max(x, y)
|
||||
if x > y then
|
||||
x
|
||||
else
|
||||
y
|
||||
end if
|
||||
end max
|
||||
|
||||
|
||||
-- maximumBy :: (a -> a -> Ordering) -> [a] -> a
|
||||
on maximumBy(f, xs)
|
||||
set cmp to mReturn(f)
|
||||
script max
|
||||
on |λ|(a, b)
|
||||
if a is missing value or cmp's |λ|(a, b) < 0 then
|
||||
b
|
||||
else
|
||||
a
|
||||
end if
|
||||
end |λ|
|
||||
end script
|
||||
|
||||
foldl(max, missing value, xs)
|
||||
end maximumBy
|
||||
|
||||
|
||||
-- Lift 2nd class handler function into 1st class script wrapper
|
||||
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
|
||||
on mReturn(f)
|
||||
if class of f is script then
|
||||
f
|
||||
else
|
||||
script
|
||||
property |λ| : f
|
||||
end script
|
||||
end if
|
||||
end mReturn
|
||||
|
||||
|
||||
-- map :: (a -> b) -> [a] -> [b]
|
||||
on map(f, xs)
|
||||
tell mReturn(f)
|
||||
set lng to length of xs
|
||||
set lst to {}
|
||||
repeat with i from 1 to lng
|
||||
set end of lst to |λ|(item i of xs, i, xs)
|
||||
end repeat
|
||||
return lst
|
||||
end tell
|
||||
end map
|
||||
|
||||
|
||||
-- pred :: Enum a => a -> a
|
||||
on pred(x)
|
||||
x - 1
|
||||
end pred
|
||||
|
||||
|
||||
-- Egyptian multiplication - progressively doubling a list, appending
|
||||
-- stages of doubling to an accumulator where needed for binary
|
||||
-- assembly of a target length
|
||||
-- replicate :: Int -> a -> [a]
|
||||
on replicate(n, a)
|
||||
set out to {}
|
||||
if n < 1 then return out
|
||||
set dbl to {a}
|
||||
|
||||
repeat while (n > 1)
|
||||
if (n mod 2) > 0 then set out to out & dbl
|
||||
set n to (n div 2)
|
||||
set dbl to (dbl & dbl)
|
||||
end repeat
|
||||
return out & dbl
|
||||
end replicate
|
||||
|
||||
|
||||
-- reverse :: [a] -> [a]
|
||||
on |reverse|(xs)
|
||||
if class of xs is text then
|
||||
(reverse of characters of xs) as text
|
||||
else
|
||||
reverse of xs
|
||||
end if
|
||||
end |reverse|
|
||||
|
||||
|
||||
-- Simplified version - assuming rows of unvarying length.
|
||||
-- transpose :: [[a]] -> [[a]]
|
||||
on transpose(rows)
|
||||
script cols
|
||||
on |λ|(_, iCol)
|
||||
script cell
|
||||
on |λ|(row)
|
||||
item iCol of row
|
||||
end |λ|
|
||||
end script
|
||||
concatMap(cell, rows)
|
||||
end |λ|
|
||||
end script
|
||||
map(cols, item 1 of rows)
|
||||
end transpose
|
||||
|
||||
|
||||
-- unlines :: [String] -> String
|
||||
on unlines(xs)
|
||||
set {dlm, my text item delimiters} to ¬
|
||||
{my text item delimiters, linefeed}
|
||||
set str to xs as text
|
||||
set my text item delimiters to dlm
|
||||
str
|
||||
end unlines
|
||||
|
||||
|
||||
-- unwords :: [String] -> String
|
||||
on unwords(xs)
|
||||
intercalateS(space, xs)
|
||||
end unwords
|
||||
28
Task/Spiral-matrix/Arturo/spiral-matrix.arturo
Normal file
28
Task/Spiral-matrix/Arturo/spiral-matrix.arturo
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
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
|
||||
]
|
||||
26
Task/Spiral-matrix/AutoHotkey/spiral-matrix.ahk
Normal file
26
Task/Spiral-matrix/AutoHotkey/spiral-matrix.ahk
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
n := 5, dx := x := y := v := 1, dy := 0
|
||||
|
||||
Loop % n*n {
|
||||
a_%x%_%y% := v++
|
||||
nx := x+dx, ny := y+dy
|
||||
If (1 > nx || nx > n || 1 > ny || ny > n || a_%nx%_%ny%)
|
||||
t := dx, dx := -dy, dy := t
|
||||
x := x+dx, y := y+dy
|
||||
}
|
||||
|
||||
Loop %n% { ; generate printout
|
||||
y := A_Index ; for each row
|
||||
Loop %n% ; and for each column
|
||||
s .= a_%A_Index%_%y% "`t" ; attach stored index
|
||||
s .= "`n" ; row is complete
|
||||
}
|
||||
MsgBox %s% ; show output
|
||||
/*
|
||||
---------------------------
|
||||
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
|
||||
---------------------------
|
||||
*/
|
||||
18
Task/Spiral-matrix/BBC-BASIC/spiral-matrix.basic
Normal file
18
Task/Spiral-matrix/BBC-BASIC/spiral-matrix.basic
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
N%=5
|
||||
@%=LENSTR$(N%*N%-1)+1
|
||||
BotCol%=0 : TopCol%=N%-1
|
||||
BotRow%=0 : TopRow%=N%-1
|
||||
DIM Matrix%(TopCol%,TopRow%)
|
||||
|
||||
Dir%=0 : Col%=0 : Row%=0
|
||||
FOR I%=0 TO N%*N%-1
|
||||
Matrix%(Col%,Row%)=I%
|
||||
PRINT TAB(Col%*@%,Row%) I%
|
||||
CASE Dir% OF
|
||||
WHEN 0: IF Col% < TopCol% THEN Col%+=1 ELSE Dir%=1 : Row%+=1 : BotRow%+=1
|
||||
WHEN 1: IF Row% < TopRow% THEN Row%+=1 ELSE Dir%=2 : Col%-=1 : TopCol%-=1
|
||||
WHEN 2: IF Col% > BotCol% THEN Col%-=1 ELSE Dir%=3 : Row%-=1 : TopRow%-=1
|
||||
WHEN 3: IF Row% > BotRow% THEN Row%-=1 ELSE Dir%=0 : Col%+=1 : BotCol%+=1
|
||||
ENDCASE
|
||||
NEXT
|
||||
END
|
||||
67
Task/Spiral-matrix/C++/spiral-matrix-1.cpp
Normal file
67
Task/Spiral-matrix/C++/spiral-matrix-1.cpp
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
#include <vector>
|
||||
#include <memory> // for auto_ptr
|
||||
#include <cmath> // for the ceil and log10 and floor functions
|
||||
#include <iostream>
|
||||
#include <iomanip> // for the setw function
|
||||
|
||||
using namespace std;
|
||||
|
||||
typedef vector< int > IntRow;
|
||||
typedef vector< IntRow > IntTable;
|
||||
|
||||
auto_ptr< IntTable > getSpiralArray( int dimension )
|
||||
{
|
||||
auto_ptr< IntTable > spiralArrayPtr( new IntTable(
|
||||
dimension, IntRow( dimension ) ) );
|
||||
|
||||
int numConcentricSquares = static_cast< int >( ceil(
|
||||
static_cast< double >( dimension ) / 2.0 ) );
|
||||
|
||||
int j;
|
||||
int sideLen = dimension;
|
||||
int currNum = 0;
|
||||
|
||||
for ( int i = 0; i < numConcentricSquares; i++ )
|
||||
{
|
||||
// do top side
|
||||
for ( j = 0; j < sideLen; j++ )
|
||||
( *spiralArrayPtr )[ i ][ i + j ] = currNum++;
|
||||
|
||||
// do right side
|
||||
for ( j = 1; j < sideLen; j++ )
|
||||
( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++;
|
||||
|
||||
// do bottom side
|
||||
for ( j = sideLen - 2; j > -1; j-- )
|
||||
( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++;
|
||||
|
||||
// do left side
|
||||
for ( j = sideLen - 2; j > 0; j-- )
|
||||
( *spiralArrayPtr )[ i + j ][ i ] = currNum++;
|
||||
|
||||
sideLen -= 2;
|
||||
}
|
||||
|
||||
return spiralArrayPtr;
|
||||
}
|
||||
|
||||
void printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr )
|
||||
{
|
||||
size_t dimension = spiralArrayPtr->size();
|
||||
|
||||
int fieldWidth = static_cast< int >( floor( log10(
|
||||
static_cast< double >( dimension * dimension - 1 ) ) ) ) + 2;
|
||||
|
||||
size_t col;
|
||||
for ( size_t row = 0; row < dimension; row++ )
|
||||
{
|
||||
for ( col = 0; col < dimension; col++ )
|
||||
cout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ];
|
||||
cout << endl;
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
printSpiralArray( getSpiralArray( 5 ) );
|
||||
}
|
||||
17
Task/Spiral-matrix/C++/spiral-matrix-2.cpp
Normal file
17
Task/Spiral-matrix/C++/spiral-matrix-2.cpp
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
#include <vector>
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
int main() {
|
||||
const int n = 5;
|
||||
const int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};
|
||||
int x = 0, y = -1, c = 0;
|
||||
vector<vector<int>> m(n, vector<int>(n));
|
||||
for (int i = 0, im = 0; i < n + n - 1; ++i, im = i % 4)
|
||||
for (int j = 0, jlen = (n + n - i) / 2; j < jlen; ++j)
|
||||
m[x += dx[im]][y += dy[im]] = ++c;
|
||||
for (auto & r : m) {
|
||||
for (auto & v : r)
|
||||
cout << v << ' ';
|
||||
cout << endl;
|
||||
}
|
||||
}
|
||||
37
Task/Spiral-matrix/C-sharp/spiral-matrix-1.cs
Normal file
37
Task/Spiral-matrix/C-sharp/spiral-matrix-1.cs
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
public int[,] Spiral(int n) {
|
||||
int[,] result = new int[n, n];
|
||||
|
||||
int pos = 0;
|
||||
int count = n;
|
||||
int value = -n;
|
||||
int sum = -1;
|
||||
|
||||
do {
|
||||
value = -1 * value / n;
|
||||
for (int i = 0; i < count; i++) {
|
||||
sum += value;
|
||||
result[sum / n, sum % n] = pos++;
|
||||
}
|
||||
value *= n;
|
||||
count--;
|
||||
for (int i = 0; i < count; i++) {
|
||||
sum += value;
|
||||
result[sum / n, sum % n] = pos++;
|
||||
}
|
||||
} while (count > 0);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
// Method to print arrays, pads numbers so they line up in columns
|
||||
public void PrintArray(int[,] array) {
|
||||
int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1;
|
||||
|
||||
for (int i = 0; i < array.GetLength(0); i++) {
|
||||
for (int j = 0; j < array.GetLength(1); j++) {
|
||||
Console.Write(array[i, j].ToString().PadLeft(n, ' '));
|
||||
}
|
||||
Console.WriteLine();
|
||||
}
|
||||
}
|
||||
21
Task/Spiral-matrix/C-sharp/spiral-matrix-2.cs
Normal file
21
Task/Spiral-matrix/C-sharp/spiral-matrix-2.cs
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
//generate spiral matrix for given N
|
||||
int[,] CreateMatrix(int n){
|
||||
int[] dx = {0, 1, 0, -1}, dy = {1, 0, -1, 0};
|
||||
int x = 0, y = -1, c = 0;
|
||||
int[,] m = new int[n,n];
|
||||
for (int i = 0, im = 0; i < n + n - 1; ++i, im = i % 4)
|
||||
for (int j = 0, jlen = (n + n - i) / 2; j < jlen; ++j)
|
||||
m[x += dx[im],y += dy[im]] = ++c;
|
||||
return n;
|
||||
}
|
||||
|
||||
//print aligned matrix
|
||||
void Print(int[,] matrix) {
|
||||
var len = (int)Math.Ceiling(Math.Log10(m.GetLength(0) * m.GetLength(1)))+1;
|
||||
for(var y = 0; y<m.GetLength(1); y++){
|
||||
for(var x = 0; x<m.GetLength(0); x++){
|
||||
Console.Write(m[y, x].ToString().PadRight(len, ' '));
|
||||
}
|
||||
Console.WriteLine();
|
||||
}
|
||||
}
|
||||
71
Task/Spiral-matrix/C-sharp/spiral-matrix-3.cs
Normal file
71
Task/Spiral-matrix/C-sharp/spiral-matrix-3.cs
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace spiralmat
|
||||
{
|
||||
class spiral
|
||||
{
|
||||
public static int lev;
|
||||
int lev_lim, count, bk, cd, low, l, m;
|
||||
spiral()
|
||||
{
|
||||
lev = lev_lim = count = bk = cd = low = l = m = 0;
|
||||
}
|
||||
|
||||
void level(int n1, int r, int c)
|
||||
{
|
||||
lev_lim = n1 % 2 == 0 ? n1 / 2 : (n1 + 1) / 2;
|
||||
if ((r <= lev_lim) && (c <= lev_lim))
|
||||
lev = Math.Min(r, c);
|
||||
else
|
||||
{
|
||||
bk = r > c ? (n1 + 1) - r : (n1 + 1) - c;
|
||||
low = Math.Min(r, c);
|
||||
if (low <= lev_lim)
|
||||
cd = low;
|
||||
lev = cd < bk ? cd : bk;
|
||||
}
|
||||
}
|
||||
|
||||
int func(int n2, int xo, int lo)
|
||||
{
|
||||
l = xo;
|
||||
m = lo;
|
||||
count = 0;
|
||||
level(n2, l, m);
|
||||
|
||||
for (int ak = 1; ak < lev; ak++)
|
||||
count += 4 * (n2 - 1 - 2 * (ak - 1));
|
||||
return count;
|
||||
}
|
||||
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
spiral ob = new spiral();
|
||||
Console.WriteLine("Enter Order..");
|
||||
int n = int.Parse(Console.ReadLine());
|
||||
Console.WriteLine("The Matrix of {0} x {1} Order is=>\n", n, n);
|
||||
for (int i = 1; i <= n; i++)
|
||||
{
|
||||
for (int j = 1; j <= n; j++)
|
||||
Console.Write("{0,3:D} ",
|
||||
ob.func(n, i, j)
|
||||
+ Convert.ToInt32(
|
||||
((j >= i) && (i == lev))
|
||||
? ((j - i) + 1)
|
||||
: ((j == ((n + 1) - lev) && (i > lev) && (i <= j)))
|
||||
? (n - 2 * (lev - 1) + (i - 1) - (n - j))
|
||||
: ((i == ((n + 1) - lev) && (j < i)))
|
||||
? ((n - 2 * (lev - 1)) + ((n - 2 * (lev - 1)) - 1) + (i - j))
|
||||
: ((j == lev) && (i > lev) && (i < ((n + 1) - lev)))
|
||||
? ((n - 2 * (lev - 1)) + ((n - 2 * (lev - 1)) - 1) + ((n - 2 * (lev - 1)) - 1) + (((n + 1) - lev) - i))
|
||||
: 0));
|
||||
Console.WriteLine();
|
||||
}
|
||||
Console.ReadKey();
|
||||
}
|
||||
}
|
||||
}
|
||||
30
Task/Spiral-matrix/C-sharp/spiral-matrix-4.cs
Normal file
30
Task/Spiral-matrix/C-sharp/spiral-matrix-4.cs
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
INPUT:-
|
||||
|
||||
Enter order..
|
||||
5
|
||||
|
||||
OUTPUT:-
|
||||
|
||||
The Matrix of 5 x 5 Order is=>
|
||||
|
||||
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
|
||||
|
||||
INPUT:-
|
||||
|
||||
Enter order..
|
||||
6
|
||||
|
||||
OUTPUT:-
|
||||
|
||||
The Matrix of 6 x 6 Order is=>
|
||||
|
||||
1 2 3 4 5 6
|
||||
20 21 22 23 24 7
|
||||
19 32 33 34 25 8
|
||||
18 31 36 35 26 9
|
||||
17 30 29 28 27 10
|
||||
16 15 14 13 12 11
|
||||
35
Task/Spiral-matrix/C/spiral-matrix-1.c
Normal file
35
Task/Spiral-matrix/C/spiral-matrix-1.c
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j]
|
||||
int main(int c, char **v)
|
||||
{
|
||||
int i, j, m = 0, n = 0;
|
||||
|
||||
/* default size: 5 */
|
||||
if (c >= 2) m = atoi(v[1]);
|
||||
if (c >= 3) n = atoi(v[2]);
|
||||
if (m <= 0) m = 5;
|
||||
if (n <= 0) n = m;
|
||||
|
||||
int **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n);
|
||||
s[0] = (int*)(s + m);
|
||||
for (i = 1; i < m; i++) s[i] = s[i - 1] + n;
|
||||
|
||||
int dx = 1, dy = 0, val = 0, t;
|
||||
for (i = j = 0; valid(i, j); i += dy, j += dx ) {
|
||||
for (; valid(i, j); j += dx, i += dy)
|
||||
s[i][j] = ++val;
|
||||
|
||||
j -= dx; i -= dy;
|
||||
t = dy; dy = dx; dx = -t;
|
||||
}
|
||||
|
||||
for (t = 2; val /= 10; t++);
|
||||
|
||||
for(i = 0; i < m; i++)
|
||||
for(j = 0; j < n || !putchar('\n'); j++)
|
||||
printf("%*d", t, s[i][j]);
|
||||
|
||||
return 0;
|
||||
}
|
||||
18
Task/Spiral-matrix/C/spiral-matrix-2.c
Normal file
18
Task/Spiral-matrix/C/spiral-matrix-2.c
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
int spiral(int w, int h, int x, int y)
|
||||
{
|
||||
return y ? w + spiral(h - 1, w, y - 1, w - x - 1) : x;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
int w = atoi(argv[1]), h = atoi(argv[2]), i, j;
|
||||
for (i = 0; i < h; i++) {
|
||||
for (j = 0; j < w; j++)
|
||||
printf("%4d", spiral(w, h, j, i));
|
||||
putchar('\n');
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
16
Task/Spiral-matrix/Clojure/spiral-matrix-1.clj
Normal file
16
Task/Spiral-matrix/Clojure/spiral-matrix-1.clj
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
(defn spiral [n]
|
||||
(let [cyc (cycle [1 n -1 (- n)])]
|
||||
(->> (range (dec n) 0 -1)
|
||||
(mapcat #(repeat 2 %))
|
||||
(cons n)
|
||||
(mapcat #(repeat %2 %) cyc)
|
||||
(reductions +)
|
||||
(map vector (range 0 (* n n)))
|
||||
(sort-by second)
|
||||
(map first)))
|
||||
|
||||
(let [n 5]
|
||||
(clojure.pprint/cl-format
|
||||
true
|
||||
(str " ~{~<~%~," (* n 3) ":;~2d ~>~}~%")
|
||||
(spiral n)))
|
||||
8
Task/Spiral-matrix/Clojure/spiral-matrix-2.clj
Normal file
8
Task/Spiral-matrix/Clojure/spiral-matrix-2.clj
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
(defn spiral-matrix [m n & [start]]
|
||||
(let [row (list (map #(+ start %) (range m)))]
|
||||
(if (= 1 n) row
|
||||
(concat row (map reverse
|
||||
(apply map list
|
||||
(spiral-matrix (dec n) m (+ start m))))))))
|
||||
|
||||
(defn spiral [n m] (spiral-matrix n m 1))
|
||||
46
Task/Spiral-matrix/CoffeeScript/spiral-matrix-1.coffee
Normal file
46
Task/Spiral-matrix/CoffeeScript/spiral-matrix-1.coffee
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
# 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
|
||||
# the upper left corner. This code computes the values for each x/y
|
||||
# coordinate of the square. (Of course, you could precompute the values
|
||||
# iteratively, but what fun is that?)
|
||||
|
||||
spiral_value = (x, y, n) ->
|
||||
prior_legs =
|
||||
N: 0
|
||||
E: 1
|
||||
S: 2
|
||||
W: 3
|
||||
|
||||
edge_run = (edge_offset) ->
|
||||
N: -> edge_offset.W - edge_offset.N
|
||||
E: -> edge_offset.N - edge_offset.E
|
||||
S: -> edge_offset.E - edge_offset.S
|
||||
W: -> edge_offset.S - edge_offset.W
|
||||
|
||||
edge_offset =
|
||||
N: y
|
||||
E: n - 1 - x
|
||||
S: n - 1 - y
|
||||
W: x
|
||||
|
||||
min_edge_offset = n
|
||||
for dir of edge_offset
|
||||
if edge_offset[dir] < min_edge_offset
|
||||
min_edge_offset = edge_offset[dir]
|
||||
border = dir
|
||||
|
||||
inner_square_edge = n - 2 * min_edge_offset
|
||||
corner_offset = n * n - inner_square_edge * inner_square_edge
|
||||
corner_offset += prior_legs[border] * (inner_square_edge - 1)
|
||||
corner_offset + edge_run(edge_offset)[border]()
|
||||
|
||||
spiral_matrix = (n) ->
|
||||
# return a nested array expression
|
||||
for y in [0...n]
|
||||
for x in [0...n]
|
||||
spiral_value x, y, n
|
||||
|
||||
do ->
|
||||
for n in [6, 7]
|
||||
console.log "\n----Spiral n=#{n}"
|
||||
console.log spiral_matrix n
|
||||
18
Task/Spiral-matrix/CoffeeScript/spiral-matrix-2.coffee
Normal file
18
Task/Spiral-matrix/CoffeeScript/spiral-matrix-2.coffee
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
> coffee spiral.coffee
|
||||
|
||||
----Spiral n=6
|
||||
[ [ 0, 1, 2, 3, 4, 5 ],
|
||||
[ 19, 20, 21, 22, 23, 6 ],
|
||||
[ 18, 31, 32, 33, 24, 7 ],
|
||||
[ 17, 30, 35, 34, 25, 8 ],
|
||||
[ 16, 29, 28, 27, 26, 9 ],
|
||||
[ 15, 14, 13, 12, 11, 10 ] ]
|
||||
|
||||
----Spiral n=7
|
||||
[ [ 0, 1, 2, 3, 4, 5, 6 ],
|
||||
[ 23, 24, 25, 26, 27, 28, 7 ],
|
||||
[ 22, 39, 40, 41, 42, 29, 8 ],
|
||||
[ 21, 38, 47, 48, 43, 30, 9 ],
|
||||
[ 20, 37, 46, 45, 44, 31, 10 ],
|
||||
[ 19, 36, 35, 34, 33, 32, 11 ],
|
||||
[ 18, 17, 16, 15, 14, 13, 12 ] ]
|
||||
18
Task/Spiral-matrix/Common-Lisp/spiral-matrix-1.lisp
Normal file
18
Task/Spiral-matrix/Common-Lisp/spiral-matrix-1.lisp
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
(defun spiral (rows columns)
|
||||
(do ((N (* rows columns))
|
||||
(spiral (make-array (list rows columns) :initial-element nil))
|
||||
(dx 1) (dy 0) (x 0) (y 0)
|
||||
(i 0 (1+ i)))
|
||||
((= i N) spiral)
|
||||
(setf (aref spiral y x) i)
|
||||
(let ((nx (+ x dx)) (ny (+ y dy)))
|
||||
(cond
|
||||
((and (< -1 nx columns)
|
||||
(< -1 ny rows)
|
||||
(null (aref spiral ny nx)))
|
||||
(setf x nx
|
||||
y ny))
|
||||
(t (psetf dx (- dy)
|
||||
dy dx)
|
||||
(setf x (+ x dx)
|
||||
y (+ y dy)))))))
|
||||
11
Task/Spiral-matrix/Common-Lisp/spiral-matrix-2.lisp
Normal file
11
Task/Spiral-matrix/Common-Lisp/spiral-matrix-2.lisp
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
(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
|
||||
;; first row, plus (n-1) x m spiral rotated 90 degrees
|
||||
(append row (map 'list #'reverse
|
||||
(apply #'mapcar #'list
|
||||
(spiral (1- n) m (+ start m))))))))
|
||||
|
||||
;; test
|
||||
(loop for row in (spiral 4 3) do
|
||||
(format t "~{~4d~^~}~%" row))
|
||||
20
Task/Spiral-matrix/D/spiral-matrix-1.d
Normal file
20
Task/Spiral-matrix/D/spiral-matrix-1.d
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
void main() {
|
||||
import std.stdio;
|
||||
enum n = 5;
|
||||
int[n][n] M;
|
||||
int pos, side = n;
|
||||
|
||||
foreach (immutable i; 0 .. n / 2 + n % 2) {
|
||||
foreach (immutable j; 0 .. side)
|
||||
M[i][i + j] = pos++;
|
||||
foreach (immutable j; 1 .. side)
|
||||
M[i + j][n - 1 - i] = pos++;
|
||||
foreach_reverse (immutable j; 0 .. side - 1)
|
||||
M[n - 1 - i][i + j] = pos++;
|
||||
foreach_reverse (immutable j; 1 .. side - 1)
|
||||
M[i + j][i] = pos++;
|
||||
side -= 2;
|
||||
}
|
||||
|
||||
writefln("%(%(%2d %)\n%)", M);
|
||||
}
|
||||
52
Task/Spiral-matrix/D/spiral-matrix-2.d
Normal file
52
Task/Spiral-matrix/D/spiral-matrix-2.d
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import std.stdio;
|
||||
|
||||
/// 2D spiral generator
|
||||
const struct Spiral {
|
||||
int w, h;
|
||||
|
||||
int opApply(int delegate(ref int, ref int, ref int) dg) {
|
||||
int idx, x, y, xy, dx = 1, dy;
|
||||
int[] subLen = [w, h-1];
|
||||
|
||||
void turn() {
|
||||
auto t = -dy;
|
||||
dy = dx;
|
||||
dx = t;
|
||||
xy = 1 - xy;
|
||||
}
|
||||
|
||||
void forward(int d = 1) {
|
||||
x += d * dx;
|
||||
y += d * dy;
|
||||
idx += d;
|
||||
}
|
||||
|
||||
Bye:
|
||||
while (true) {
|
||||
if (subLen[xy] == 0)
|
||||
break;
|
||||
foreach (_; 0 .. subLen[xy]--)
|
||||
if (dg(idx, x, y))
|
||||
break Bye;
|
||||
else
|
||||
forward();
|
||||
forward(-1);
|
||||
turn();
|
||||
forward();
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
int[][] spiralMatrix(int w, int h) {
|
||||
auto m = new typeof(return)(h, w);
|
||||
foreach (value, x, y; Spiral(w, h))
|
||||
m[y][x] = value;
|
||||
return m;
|
||||
}
|
||||
|
||||
void main() {
|
||||
foreach (r; spiralMatrix(9, 4))
|
||||
writefln("%(%2d %)", r);
|
||||
}
|
||||
56
Task/Spiral-matrix/DCL/spiral-matrix.dcl
Normal file
56
Task/Spiral-matrix/DCL/spiral-matrix.dcl
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
$ p1 = f$integer( p1 )
|
||||
$ max = p1 * p1
|
||||
$
|
||||
$ i = 0
|
||||
$ r = 1
|
||||
$ rd = 0
|
||||
$ c = 1
|
||||
$ cd = 1
|
||||
$ loop:
|
||||
$ a'r'_'c' = i
|
||||
$ nr = r + rd
|
||||
$ nc = c + cd
|
||||
$ if nr .eq. 0 .or. nc .eq. 0 .or. nr .gt. p1 .or. nc .gt. p1 .or. f$type( a'nr'_'nc' ) .nes. ""
|
||||
$ then
|
||||
$ gosub change_directions
|
||||
$ endif
|
||||
$ r = r + rd
|
||||
$ c = c + cd
|
||||
$ i = i + 1
|
||||
$ if i .lt. max then $ goto loop
|
||||
$ length = f$length( f$string( max - 1 ))
|
||||
$ r = 1
|
||||
$ loop2:
|
||||
$ c = 1
|
||||
$ output = ""
|
||||
$ loop3:
|
||||
$ output = output + f$fao( "!#UL ", length, a'r'_'c' )
|
||||
$ c = c + 1
|
||||
$ if c .le. p1 then $ goto loop3
|
||||
$ write sys$output output
|
||||
$ r = r + 1
|
||||
$ if r .le. p1 then $ goto loop2
|
||||
$ exit
|
||||
$
|
||||
$ change_directions:
|
||||
$ if rd .eq. 0 .and cd .eq. 1
|
||||
$ then
|
||||
$ rd = 1
|
||||
$ cd = 0
|
||||
$ else
|
||||
$ if rd .eq. 1 .and. cd .eq. 0
|
||||
$ then
|
||||
$ rd = 0
|
||||
$ cd = -1
|
||||
$ else
|
||||
$ if rd .eq. 0 .and. cd .eq. -1
|
||||
$ then
|
||||
$ rd = -1
|
||||
$ cd = 0
|
||||
$ else
|
||||
$ rd = 0
|
||||
$ cd = 1
|
||||
$ endif
|
||||
$ endif
|
||||
$ endif
|
||||
$ return
|
||||
87
Task/Spiral-matrix/Delphi/spiral-matrix.delphi
Normal file
87
Task/Spiral-matrix/Delphi/spiral-matrix.delphi
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
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;
|
||||
25
Task/Spiral-matrix/E/spiral-matrix-1.e
Normal file
25
Task/Spiral-matrix/E/spiral-matrix-1.e
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
def spiral(size) {
|
||||
def array := makeFlex2DArray(size, size)
|
||||
var i := -1 # Counter of numbers to fill
|
||||
var p := makeVector2(0, 0) # "Position"
|
||||
var dp := makeVector2(1, 0) # "Velocity"
|
||||
|
||||
# If the cell we were to fill next (even after turning) is full, we're done.
|
||||
while (array[p.y(), p.x()] == null) {
|
||||
|
||||
array[p.y(), p.x()] := (i += 1) # Fill cell
|
||||
def next := p + dp # Look forward
|
||||
|
||||
# If the cell we were to fill next is already full, then turn clockwise.
|
||||
# Gimmick: If we hit the edges of the array, by the modulo we wrap around
|
||||
# and see the already-filled cell on the opposite edge.
|
||||
if (array[next.y() %% size, next.x() %% size] != null) {
|
||||
dp := dp.clockwise()
|
||||
}
|
||||
|
||||
# Move forward
|
||||
p += dp
|
||||
}
|
||||
|
||||
return array
|
||||
}
|
||||
6
Task/Spiral-matrix/E/spiral-matrix-2.e
Normal file
6
Task/Spiral-matrix/E/spiral-matrix-2.e
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
? 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
|
||||
19
Task/Spiral-matrix/Elixir/spiral-matrix-1.elixir
Normal file
19
Task/Spiral-matrix/Elixir/spiral-matrix-1.elixir
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
defmodule RC do
|
||||
def spiral_matrix(n) do
|
||||
wide = length(to_char_list(n*n-1))
|
||||
fmt = String.duplicate("~#{wide}w ", n) <> "~n"
|
||||
runs = Enum.flat_map(n..1, &[&1,&1]) |> tl
|
||||
delta = Stream.cycle([{0,1},{1,0},{0,-1},{-1,0}])
|
||||
running(Enum.zip(runs,delta),0,-1,[])
|
||||
|> Enum.with_index |> Enum.sort |> Enum.chunk(n)
|
||||
|> Enum.each(fn row -> :io.format fmt, (for {_,i} <- row, do: i) end)
|
||||
end
|
||||
|
||||
defp running([{run,{dx,dy}}|rest], x, y, track) do
|
||||
new_track = Enum.reduce(1..run, track, fn i,acc -> [{x+i*dx, y+i*dy} | acc] end)
|
||||
running(rest, x+run*dx, y+run*dy, new_track)
|
||||
end
|
||||
defp running([],_,_,track), do: track |> Enum.reverse
|
||||
end
|
||||
|
||||
RC.spiral_matrix(5)
|
||||
30
Task/Spiral-matrix/Elixir/spiral-matrix-2.elixir
Normal file
30
Task/Spiral-matrix/Elixir/spiral-matrix-2.elixir
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
defmodule RC do
|
||||
def spiral_matrix(n) do
|
||||
wide = String.length(to_string(n*n-1))
|
||||
fmt = String.duplicate("~#{wide}w ", n) <> "~n"
|
||||
right(n,n-1,0,[]) |> Enum.reverse |> Enum.with_index |> Enum.sort |> Enum.chunk(n) |>
|
||||
Enum.each(fn row ->
|
||||
:io.format fmt, (for {_,i} <- row, do: i)
|
||||
end)
|
||||
end
|
||||
|
||||
def right(n, side, i, coordinates) do
|
||||
down(n, side, i, Enum.reduce(0..side, coordinates, fn j,acc -> [{i, i+j} | acc] end))
|
||||
end
|
||||
|
||||
def down(_, 0, _, coordinates), do: coordinates
|
||||
def down(n, side, i, coordinates) do
|
||||
left(n, side-1, i, Enum.reduce(1..side, coordinates, fn j,acc -> [{i+j, n-1-i} | acc] end))
|
||||
end
|
||||
|
||||
def left(n, side, i, coordinates) do
|
||||
up(n, side, i, Enum.reduce(side..0, coordinates, fn j,acc -> [{n-1-i, i+j} | acc] end))
|
||||
end
|
||||
|
||||
def up(_, 0, _, coordinates), do: coordinates
|
||||
def up(n, side, i, coordinates) do
|
||||
right(n, side-1, i+1, Enum.reduce(side..1, coordinates, fn j,acc -> [{i+j, i} | acc] end))
|
||||
end
|
||||
end
|
||||
|
||||
RC.spiral_matrix(5)
|
||||
19
Task/Spiral-matrix/Elixir/spiral-matrix-3.elixir
Normal file
19
Task/Spiral-matrix/Elixir/spiral-matrix-3.elixir
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
defmodule RC do
|
||||
def spiral_matrix(n) do
|
||||
fmt = String.duplicate("~#{length(to_char_list(n*n-1))}w ", n) <> "~n"
|
||||
Enum.flat_map(n..1, &[&1, &1])
|
||||
|> tl
|
||||
|> Enum.reduce({{0,-1},{0,1},[]}, fn run,{{x,y},{dx,dy},acc} ->
|
||||
side = for i <- 1..run, do: {x+i*dx, y+i*dy}
|
||||
{{x+run*dx, y+run*dy}, {dy, -dx}, acc++side}
|
||||
end)
|
||||
|> elem(2)
|
||||
|> Enum.with_index
|
||||
|> Enum.sort
|
||||
|> Enum.map(fn {_,i} -> i end)
|
||||
|> Enum.chunk(n)
|
||||
|> Enum.each(fn row -> :io.format fmt, row end)
|
||||
end
|
||||
end
|
||||
|
||||
RC.spiral_matrix(5)
|
||||
29
Task/Spiral-matrix/Euphoria/spiral-matrix.euphoria
Normal file
29
Task/Spiral-matrix/Euphoria/spiral-matrix.euphoria
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
function spiral(integer dimension)
|
||||
integer side, curr, curr2
|
||||
sequence s
|
||||
s = repeat(repeat(0,dimension),dimension)
|
||||
side = dimension
|
||||
curr = 0
|
||||
for i = 0 to floor(dimension/2) do
|
||||
for j = 1 to side-1 do
|
||||
s[i+1][i+j] = curr -- top
|
||||
curr2 = curr + side-1
|
||||
s[i+j][i+side] = curr2 -- right
|
||||
curr2 += side-1
|
||||
s[i+side][i+side-j+1] = curr2 -- bottom
|
||||
curr2 += side-1
|
||||
s[i+side-j+1][i+1] = curr2 -- left
|
||||
curr += 1
|
||||
end for
|
||||
curr = curr2 + 1
|
||||
side -= 2
|
||||
end for
|
||||
|
||||
if remainder(dimension,2) then
|
||||
s[floor(dimension/2)+1][floor(dimension/2)+1] = curr
|
||||
end if
|
||||
|
||||
return s
|
||||
end function
|
||||
|
||||
? spiral(5)
|
||||
14
Task/Spiral-matrix/F-Sharp/spiral-matrix.fs
Normal file
14
Task/Spiral-matrix/F-Sharp/spiral-matrix.fs
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
let Spiral n =
|
||||
let sq = Array2D.create n n 0 // Set up an output array
|
||||
let nCur = ref -1 // Current value being inserted
|
||||
let NextN() = nCur := (!nCur+1) ; !nCur // Inc current value and return new value
|
||||
let Frame inset = // Create the "frame" at an offset from the outside
|
||||
let rangeF = [inset..(n - inset - 2)] // Range we use going forward
|
||||
let rangeR = [(n - inset - 1)..(-1)..(inset + 1)] // Range we use going backward
|
||||
rangeF |> Seq.iter (fun i -> sq.[inset,i] <- NextN()) // Top of frame
|
||||
rangeF |> Seq.iter (fun i -> sq.[i,n-inset-1] <- NextN()) // Right side of frame
|
||||
rangeR |> Seq.iter (fun i -> sq.[n-inset-1,i] <- NextN()) // Bottom of frame
|
||||
rangeR |> Seq.iter (fun i -> sq.[i,inset] <- NextN()) // Left side of frame
|
||||
[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
|
||||
19
Task/Spiral-matrix/Factor/spiral-matrix.factor
Normal file
19
Task/Spiral-matrix/Factor/spiral-matrix.factor
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
USING: arrays grouping io kernel math math.combinatorics
|
||||
math.ranges math.statistics prettyprint sequences
|
||||
sequences.repeating ;
|
||||
IN: rosetta-code.spiral-matrix
|
||||
|
||||
: counts ( n -- seq ) 1 [a,b] 2 repeat rest ;
|
||||
|
||||
: vals ( n -- seq )
|
||||
[ 1 swap 2dup [ neg ] bi@ 4array ] [ 2 * 1 - cycle ] bi ;
|
||||
|
||||
: evJKT2 ( n -- seq )
|
||||
[ counts ] [ vals ] bi [ <array> ] 2map concat ;
|
||||
|
||||
: spiral ( n -- matrix )
|
||||
[ evJKT2 cum-sum inverse-permutation ] [ group ] bi ;
|
||||
|
||||
: spiral-demo ( -- ) 5 9 [ spiral simple-table. nl ] bi@ ;
|
||||
|
||||
MAIN: spiral-demo
|
||||
49
Task/Spiral-matrix/Fortran/spiral-matrix.f
Normal file
49
Task/Spiral-matrix/Fortran/spiral-matrix.f
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
PROGRAM SPIRAL
|
||||
|
||||
IMPLICIT NONE
|
||||
|
||||
INTEGER, PARAMETER :: size = 5
|
||||
INTEGER :: i, x = 0, y = 1, count = size, n = 0
|
||||
INTEGER :: array(size,size)
|
||||
|
||||
DO i = 1, count
|
||||
x = x + 1
|
||||
array(x,y) = n
|
||||
n = n + 1
|
||||
END DO
|
||||
|
||||
DO
|
||||
count = count - 1
|
||||
DO i = 1, count
|
||||
y = y + 1
|
||||
array(x,y) = n
|
||||
n = n + 1
|
||||
END DO
|
||||
DO i = 1, count
|
||||
x = x - 1
|
||||
array(x,y) = n
|
||||
n = n + 1
|
||||
END DO
|
||||
IF (n > size*size-1) EXIT
|
||||
count = count - 1
|
||||
DO i = 1, count
|
||||
y = y - 1
|
||||
array(x,y) = n
|
||||
n = n + 1
|
||||
END DO
|
||||
DO i = 1, count
|
||||
x = x + 1
|
||||
array(x,y) = n
|
||||
n = n + 1
|
||||
END DO
|
||||
IF (n > size*size-1) EXIT
|
||||
END DO
|
||||
|
||||
DO y = 1, size
|
||||
DO x = 1, size
|
||||
WRITE (*, "(I4)", ADVANCE="NO") array (x, y)
|
||||
END DO
|
||||
WRITE (*,*)
|
||||
END DO
|
||||
|
||||
END PROGRAM SPIRAL
|
||||
76
Task/Spiral-matrix/FreeBASIC/spiral-matrix.basic
Normal file
76
Task/Spiral-matrix/FreeBASIC/spiral-matrix.basic
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
' FB 1.05.0 Win64
|
||||
|
||||
Enum Direction
|
||||
across
|
||||
down
|
||||
back
|
||||
up
|
||||
End Enum
|
||||
|
||||
Dim As Integer n
|
||||
|
||||
Do
|
||||
Input "Enter size of matrix "; n
|
||||
Loop Until n > 0
|
||||
|
||||
Dim spiral(1 To n, 1 To n) As Integer '' all zero by default
|
||||
|
||||
' enter the numbers 0 to (n^2 - 1) spirally in the matrix
|
||||
|
||||
Dim As Integer row = 1, col = 1, lowRow = 1, highRow = n, lowCol = 1, highCol = n
|
||||
Dim d As Direction = across
|
||||
|
||||
For i As Integer = 0 To (n * n - 1)
|
||||
spiral(row, col) = i
|
||||
Select Case d
|
||||
Case across
|
||||
col += 1
|
||||
If col > highCol Then
|
||||
col = highCol
|
||||
row += 1
|
||||
d = down
|
||||
End if
|
||||
Case down
|
||||
row += 1
|
||||
If row > highRow Then
|
||||
row = highRow
|
||||
col -= 1
|
||||
d = back
|
||||
End if
|
||||
Case back
|
||||
col -= 1
|
||||
If col < lowCol Then
|
||||
col = lowCol
|
||||
row -= 1
|
||||
d = up
|
||||
lowRow += 1
|
||||
End If
|
||||
Case up
|
||||
row -= 1
|
||||
If row < lowRow Then
|
||||
row = lowRow
|
||||
col += 1
|
||||
d = across
|
||||
highRow -= 1
|
||||
lowCol += 1
|
||||
highCol -= 1
|
||||
End If
|
||||
End Select
|
||||
Next
|
||||
|
||||
' print spiral matrix if n < 20
|
||||
Print
|
||||
If n < 20 Then
|
||||
For i As Integer = 1 To n
|
||||
For j As Integer = 1 To n
|
||||
Print Using "####"; spiral(i, j);
|
||||
Next j
|
||||
Print
|
||||
Next i
|
||||
Else
|
||||
Print "Matrix is too big to display on 80 column console"
|
||||
End If
|
||||
|
||||
Print
|
||||
Print "Press any key to quit"
|
||||
Sleep
|
||||
47
Task/Spiral-matrix/GAP/spiral-matrix.gap
Normal file
47
Task/Spiral-matrix/GAP/spiral-matrix.gap
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
# 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;
|
||||
a := NullMat(n, n);
|
||||
vi := [ 1, 0, -1, 0 ];
|
||||
vj := [ 0, 1, 0, -1 ];
|
||||
imin := 0;
|
||||
imax := n;
|
||||
jmin := 1;
|
||||
jmax := n + 1;
|
||||
p := 1;
|
||||
di := vi[p];
|
||||
dj := vj[p];
|
||||
i := 1;
|
||||
j := 1;
|
||||
for k in [1 .. n*n] do
|
||||
a[j][i] := k;
|
||||
i := i + di;
|
||||
j := j + dj;
|
||||
if i < imin or i > imax or j < jmin or j > jmax then
|
||||
i := i - di;
|
||||
j := j - dj;
|
||||
p := RemInt(p, 4) + 1;
|
||||
di := vi[p];
|
||||
dj := vj[p];
|
||||
i := i + di;
|
||||
j := j + dj;
|
||||
if p = 1 then
|
||||
imax := imax - 1;
|
||||
elif p = 2 then
|
||||
jmax := jmax - 1;
|
||||
elif p = 3 then
|
||||
imin := imin + 1;
|
||||
else
|
||||
jmin := jmin + 1;
|
||||
fi;
|
||||
fi;
|
||||
od;
|
||||
return a;
|
||||
end;
|
||||
|
||||
PrintArray(SpiralMatrix(5));
|
||||
# [ [ 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 ] ]
|
||||
58
Task/Spiral-matrix/Go/spiral-matrix.go
Normal file
58
Task/Spiral-matrix/Go/spiral-matrix.go
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
var n = 5
|
||||
|
||||
func main() {
|
||||
if n < 1 {
|
||||
return
|
||||
}
|
||||
top, left, bottom, right := 0, 0, n-1, n-1
|
||||
sz := n * n
|
||||
a := make([]int, sz)
|
||||
i := 0
|
||||
for left < right {
|
||||
// work right, along top
|
||||
for c := left; c <= right; c++ {
|
||||
a[top*n+c] = i
|
||||
i++
|
||||
}
|
||||
top++
|
||||
// work down right side
|
||||
for r := top; r <= bottom; r++ {
|
||||
a[r*n+right] = i
|
||||
i++
|
||||
}
|
||||
right--
|
||||
if top == bottom {
|
||||
break
|
||||
}
|
||||
// work left, along bottom
|
||||
for c := right; c >= left; c-- {
|
||||
a[bottom*n+c] = i
|
||||
i++
|
||||
}
|
||||
bottom--
|
||||
// work up left side
|
||||
for r := bottom; r >= top; r-- {
|
||||
a[r*n+left] = i
|
||||
i++
|
||||
}
|
||||
left++
|
||||
}
|
||||
// center (last) element
|
||||
a[top*n+left] = i
|
||||
|
||||
// print
|
||||
w := len(strconv.Itoa(n*n - 1))
|
||||
for i, e := range a {
|
||||
fmt.Printf("%*d ", w, e)
|
||||
if i%n == n-1 {
|
||||
fmt.Println("")
|
||||
}
|
||||
}
|
||||
}
|
||||
54
Task/Spiral-matrix/Groovy/spiral-matrix-1.groovy
Normal file
54
Task/Spiral-matrix/Groovy/spiral-matrix-1.groovy
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
enum Direction {
|
||||
East([0,1]), South([1,0]), West([0,-1]), North([-1,0]);
|
||||
private static _n
|
||||
private final stepDelta
|
||||
private bound
|
||||
|
||||
private Direction(delta) {
|
||||
stepDelta = delta
|
||||
}
|
||||
|
||||
public static setN(int n) {
|
||||
Direction._n = n
|
||||
North.bound = 0
|
||||
South.bound = n-1
|
||||
West.bound = 0
|
||||
East.bound = n-1
|
||||
}
|
||||
|
||||
public List move(i, j) {
|
||||
def dir = this
|
||||
def newIJDir = [[i,j],stepDelta].transpose().collect { it.sum() } + dir
|
||||
if (((North.bound)..(South.bound)).contains(newIJDir[0])
|
||||
&& ((West.bound)..(East.bound)).contains(newIJDir[1])) {
|
||||
newIJDir
|
||||
} else {
|
||||
(++dir).move(i, j)
|
||||
}
|
||||
}
|
||||
|
||||
public Object next() {
|
||||
switch (this) {
|
||||
case North: West.bound++; return East;
|
||||
case East: North.bound++; return South;
|
||||
case South: East.bound--; return West;
|
||||
case West: South.bound--; return North;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
def spiralMatrix = { n ->
|
||||
if (n < 1) return []
|
||||
def M = (0..<n).collect { [0]*n }
|
||||
def i = 0
|
||||
def j = 0
|
||||
Direction.n = n
|
||||
def dir = Direction.East
|
||||
(0..<(n**2)).each { k ->
|
||||
M[i][j] = k
|
||||
(i,j,dir) = (k < (n**2 - 1)) \
|
||||
? dir.move(i,j) \
|
||||
: [i,j,dir]
|
||||
}
|
||||
M
|
||||
}
|
||||
7
Task/Spiral-matrix/Groovy/spiral-matrix-2.groovy
Normal file
7
Task/Spiral-matrix/Groovy/spiral-matrix-2.groovy
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
(1..10).each { n ->
|
||||
spiralMatrix(n).each { row ->
|
||||
row.each { printf "%5d", it }
|
||||
println()
|
||||
}
|
||||
println ()
|
||||
}
|
||||
9
Task/Spiral-matrix/Haskell/spiral-matrix-1.hs
Normal file
9
Task/Spiral-matrix/Haskell/spiral-matrix-1.hs
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
import Data.List
|
||||
import Control.Monad
|
||||
grade xs = map snd. sort $ zip xs [0..]
|
||||
values n = cycle [1,n,-1,-n]
|
||||
counts n = (n:).concatMap (ap (:) return) $ [n-1,n-2..1]
|
||||
reshape n = unfoldr (\xs -> if null xs then Nothing else Just (splitAt n xs))
|
||||
spiral n = reshape n . grade. scanl1 (+). concat $ zipWith replicate (counts n) (values n)
|
||||
displayRow = putStrLn . intercalate " " . map show
|
||||
main = mapM displayRow $ spiral 5
|
||||
9
Task/Spiral-matrix/Haskell/spiral-matrix-2.hs
Normal file
9
Task/Spiral-matrix/Haskell/spiral-matrix-2.hs
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
import Data.List
|
||||
import Control.Applicative
|
||||
counts = tail . reverse . concat . map (replicate 2) . enumFromTo 1
|
||||
values = cycle . ((++) <$> map id <*> map negate) . (1 :) . (: [])
|
||||
grade = map snd . sort . flip zip [0..]
|
||||
copies = grade . scanl1 (+) . concat . map (uncurry replicate) . (zip <$> counts <*> values)
|
||||
parts = (<*>) take $ (.) <$> (map . take) <*> (iterate . drop) <*> copies
|
||||
disp = (>> return ()) . mapM (putStrLn . intercalate " " . map show) . parts
|
||||
main = disp 5
|
||||
10
Task/Spiral-matrix/Haskell/spiral-matrix-3.hs
Normal file
10
Task/Spiral-matrix/Haskell/spiral-matrix-3.hs
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import Data.List (transpose)
|
||||
import Text.Printf (printf)
|
||||
|
||||
-- spiral is the first row plus a smaller spiral rotated 90 deg
|
||||
spiral 0 _ _ = [[]]
|
||||
spiral h w s = [s .. s+w-1] : rot90 (spiral w (h-1) (s+w))
|
||||
where rot90 = (map reverse).transpose
|
||||
|
||||
-- this is sort of hideous, someone may want to fix it
|
||||
main = mapM_ (\row->mapM_ ((printf "%4d").toInteger) row >> putStrLn "") (spiral 10 9 1)
|
||||
30
Task/Spiral-matrix/Haskell/spiral-matrix-4.hs
Normal file
30
Task/Spiral-matrix/Haskell/spiral-matrix-4.hs
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import Data.List (intercalate, transpose)
|
||||
|
||||
---------------------- SPIRAL MATRIX ---------------------
|
||||
spiral :: Int -> [[Int]]
|
||||
spiral n = go n n 0
|
||||
where
|
||||
go rows cols x
|
||||
| 0 < rows =
|
||||
[x .. pred cols + x] :
|
||||
fmap
|
||||
reverse
|
||||
(transpose $ go cols (pred rows) (x + cols))
|
||||
| otherwise = [[]]
|
||||
|
||||
|
||||
--------------------------- TEST -------------------------
|
||||
main :: IO ()
|
||||
main = putStrLn $ wikiTable $ spiral 5
|
||||
|
||||
|
||||
--------------------- TABLE FORMATTING -------------------
|
||||
wikiTable :: Show a => [[a]] -> String
|
||||
wikiTable =
|
||||
concat
|
||||
. ("{| class=\"wikitable\" style=\"text-align: right;" :)
|
||||
. ("width:12em;height:12em;table-layout:fixed;\"\n|-\n" :)
|
||||
. return
|
||||
. (<> "\n|}")
|
||||
. intercalate "\n|-\n"
|
||||
. fmap (('|' :) . (' ' :) . intercalate " || " . fmap show)
|
||||
46
Task/Spiral-matrix/IS-BASIC/spiral-matrix.basic
Normal file
46
Task/Spiral-matrix/IS-BASIC/spiral-matrix.basic
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
100 PROGRAM "SpiralMa.bas"
|
||||
110 TEXT 80
|
||||
120 INPUT PROMPT "Enter size of matrix (max. 10): ":N
|
||||
130 NUMERIC A(1 TO N,1 TO N)
|
||||
140 CALL INIT(A)
|
||||
150 CALL WRITE(A)
|
||||
160 DEF INIT(REF T)
|
||||
170 LET BCOL,BROW,COL,ROW=1:LET TCOL,TROW=N:LET DIR=0
|
||||
180 FOR I=0 TO N^2-1
|
||||
190 LET T(COL,ROW)=I
|
||||
200 SELECT CASE DIR
|
||||
210 CASE 0
|
||||
220 IF ROW<TROW THEN
|
||||
230 LET ROW=ROW+1
|
||||
240 ELSE
|
||||
250 LET DIR=1:LET COL=COL+1:LET BCOL=BCOL+1
|
||||
260 END IF
|
||||
270 CASE 1
|
||||
280 IF COL<TCOL THEN
|
||||
290 LET COL=COL+1
|
||||
300 ELSE
|
||||
310 LET DIR=2:LET ROW=ROW-1:LET TROW=TROW-1
|
||||
320 END IF
|
||||
330 CASE 2
|
||||
340 IF ROW>BROW THEN
|
||||
350 LET ROW=ROW-1
|
||||
360 ELSE
|
||||
370 LET DIR=3:LET COL=COL-1:LET TCOL=TCOL-1
|
||||
380 END IF
|
||||
390 CASE 3
|
||||
400 IF COL>BCOL THEN
|
||||
410 LET COL=COL-1
|
||||
420 ELSE
|
||||
430 LET DIR=0:LET ROW=ROW+1:LET BROW=BROW+1
|
||||
440 END IF
|
||||
450 END SELECT
|
||||
460 NEXT
|
||||
470 END DEF
|
||||
480 DEF WRITE(REF T)
|
||||
490 FOR I=LBOUND(T,1) TO UBOUND(T,1)
|
||||
500 FOR J=LBOUND(T,2) TO UBOUND(T,2)
|
||||
510 PRINT USING " ##":T(I,J);
|
||||
520 NEXT
|
||||
530 PRINT
|
||||
540 NEXT
|
||||
550 END DEF
|
||||
28
Task/Spiral-matrix/Icon/spiral-matrix.icon
Normal file
28
Task/Spiral-matrix/Icon/spiral-matrix.icon
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
procedure main(A) # spiral matrix
|
||||
N := 0 < integer(\A[1]|5) # N=1... (dfeault 5)
|
||||
WriteMatrix(SpiralMatrix(N))
|
||||
end
|
||||
|
||||
procedure WriteMatrix(M) #: write the matrix
|
||||
every x := M[r := 1 to *M, c := 1 to *M[r]] do
|
||||
writes(right(\x|"-", 3), if c = *M[r] then "\n" else "")
|
||||
return
|
||||
end
|
||||
|
||||
procedure SpiralMatrix(N) #: create spiral matrix
|
||||
every (!(M := list(N))):= list(N) # build empty matrix NxN
|
||||
# setup before starting first turn
|
||||
corner := 0 # . corner we're at
|
||||
i := -1 # . cell contents
|
||||
r:= 1 ; c :=0 # . row & col
|
||||
cincr := integer(sin(0)) # . column incr
|
||||
|
||||
until i > N^2 do {
|
||||
rincr := cincr # row incr follows col
|
||||
cincr := integer(sin(&pi/2*(corner+:=1))) # col incr at each corner
|
||||
if (run := N-corner/2) = 0 then break # shorten run to 0 at U/R & L/L
|
||||
every run to 1 by -1 do
|
||||
M[r +:= rincr,c +:= cincr] := i +:= 1 # move, count, and fill
|
||||
}
|
||||
return M
|
||||
end
|
||||
8
Task/Spiral-matrix/J/spiral-matrix.j
Normal file
8
Task/Spiral-matrix/J/spiral-matrix.j
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
spiral =: ,~ $ [: /: }.@(2 # >:@i.@-) +/\@# <:@+: $ (, -)@(1&,)
|
||||
|
||||
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
|
||||
51
Task/Spiral-matrix/Java/spiral-matrix.java
Normal file
51
Task/Spiral-matrix/Java/spiral-matrix.java
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
public class Blah {
|
||||
|
||||
public static void main(String[] args) {
|
||||
print2dArray(getSpiralArray(5));
|
||||
}
|
||||
|
||||
public static int[][] getSpiralArray(int dimension) {
|
||||
int[][] spiralArray = new int[dimension][dimension];
|
||||
|
||||
int numConcentricSquares = (int) Math.ceil((dimension) / 2.0);
|
||||
|
||||
int j;
|
||||
int sideLen = dimension;
|
||||
int currNum = 0;
|
||||
|
||||
for (int i = 0; i < numConcentricSquares; i++) {
|
||||
// do top side
|
||||
for (j = 0; j < sideLen; j++) {
|
||||
spiralArray[i][i + j] = currNum++;
|
||||
}
|
||||
|
||||
// do right side
|
||||
for (j = 1; j < sideLen; j++) {
|
||||
spiralArray[i + j][dimension - 1 - i] = currNum++;
|
||||
}
|
||||
|
||||
// do bottom side
|
||||
for (j = sideLen - 2; j > -1; j--) {
|
||||
spiralArray[dimension - 1 - i][i + j] = currNum++;
|
||||
}
|
||||
|
||||
// do left side
|
||||
for (j = sideLen - 2; j > 0; j--) {
|
||||
spiralArray[i + j][i] = currNum++;
|
||||
}
|
||||
|
||||
sideLen -= 2;
|
||||
}
|
||||
|
||||
return spiralArray;
|
||||
}
|
||||
|
||||
public static void print2dArray(int[][] array) {
|
||||
for (int[] row : array) {
|
||||
for (int elem : row) {
|
||||
System.out.printf("%3d", elem);
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
}
|
||||
21
Task/Spiral-matrix/JavaScript/spiral-matrix-1.js
Normal file
21
Task/Spiral-matrix/JavaScript/spiral-matrix-1.js
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
spiralArray = function (edge) {
|
||||
var arr = Array(edge),
|
||||
x = 0, y = edge,
|
||||
total = edge * edge--,
|
||||
dx = 1, dy = 0,
|
||||
i = 0, j = 0;
|
||||
while (y) arr[--y] = [];
|
||||
while (i < total) {
|
||||
arr[y][x] = i++;
|
||||
x += dx; y += dy;
|
||||
if (++j == edge) {
|
||||
if (dy < 0) {x++; y++; edge -= 2}
|
||||
j = dx; dx = -dy; dy = j; j = 0;
|
||||
}
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
// T E S T:
|
||||
arr = spiralArray(edge = 5);
|
||||
for (y= 0; y < edge; y++) console.log(arr[y].join(" "));
|
||||
67
Task/Spiral-matrix/JavaScript/spiral-matrix-2.js
Normal file
67
Task/Spiral-matrix/JavaScript/spiral-matrix-2.js
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
(function (n) {
|
||||
|
||||
// Spiral: the first row plus a smaller spiral rotated 90 degrees clockwise
|
||||
function spiral(lngRows, lngCols, nStart) {
|
||||
return lngRows ? [range(nStart, (nStart + lngCols) - 1)].concat(
|
||||
transpose(
|
||||
spiral(lngCols, lngRows - 1, nStart + lngCols)
|
||||
).map(reverse)
|
||||
) : [
|
||||
[]
|
||||
];
|
||||
}
|
||||
|
||||
// rows and columns transposed (for 90 degree rotation)
|
||||
function transpose(lst) {
|
||||
return lst.length > 1 ? lst[0].map(function (_, col) {
|
||||
return lst.map(function (row) {
|
||||
return row[col];
|
||||
});
|
||||
}) : lst;
|
||||
}
|
||||
|
||||
// elements in reverse order (for 90 degree rotation)
|
||||
function reverse(lst) {
|
||||
return lst.length > 1 ? lst.reduceRight(function (acc, x) {
|
||||
return acc.concat(x);
|
||||
}, []) : lst;
|
||||
}
|
||||
|
||||
// [m..n]
|
||||
function range(m, n) {
|
||||
return Array.apply(null, Array(n - m + 1)).map(function (x, i) {
|
||||
return m + i;
|
||||
});
|
||||
}
|
||||
|
||||
// TESTING
|
||||
|
||||
var lstSpiral = spiral(n, n, 0);
|
||||
|
||||
|
||||
// OUTPUT FORMATTING - JSON and wikiTable
|
||||
function wikiTable(lstRows, blnHeaderRow, strStyle) {
|
||||
return '{| class="wikitable" ' + (
|
||||
strStyle ? 'style="' + strStyle + '"' : ''
|
||||
) + lstRows.map(function (lstRow, iRow) {
|
||||
var strDelim = ((blnHeaderRow && !iRow) ? '!' : '|');
|
||||
|
||||
return '\n|-\n' + strDelim + ' ' + lstRow.map(function (v) {
|
||||
return typeof v === 'undefined' ? ' ' : v;
|
||||
}).join(' ' + strDelim + strDelim + ' ');
|
||||
}).join('') + '\n|}';
|
||||
}
|
||||
|
||||
return [
|
||||
wikiTable(
|
||||
|
||||
lstSpiral,
|
||||
|
||||
false,
|
||||
'text-align:center;width:12em;height:12em;table-layout:fixed;'
|
||||
),
|
||||
|
||||
JSON.stringify(lstSpiral)
|
||||
].join('\n\n');
|
||||
|
||||
})(5);
|
||||
1
Task/Spiral-matrix/JavaScript/spiral-matrix-3.js
Normal file
1
Task/Spiral-matrix/JavaScript/spiral-matrix-3.js
Normal file
|
|
@ -0,0 +1 @@
|
|||
[[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]]
|
||||
88
Task/Spiral-matrix/JavaScript/spiral-matrix-4.js
Normal file
88
Task/Spiral-matrix/JavaScript/spiral-matrix-4.js
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
(() => {
|
||||
"use strict";
|
||||
|
||||
// ------------------ SPIRAL MATRIX ------------------
|
||||
|
||||
// spiral :: Int -> [[Int]]
|
||||
const spiral = n => {
|
||||
const go = (rows, cols, start) =>
|
||||
Boolean(rows) ? [
|
||||
enumFromTo(start)(start + pred(cols)),
|
||||
...transpose(
|
||||
go(
|
||||
cols,
|
||||
pred(rows),
|
||||
start + cols
|
||||
)
|
||||
).map(reverse)
|
||||
] : [
|
||||
[]
|
||||
];
|
||||
|
||||
return go(n, n, 0);
|
||||
};
|
||||
|
||||
|
||||
// ---------------------- TEST -----------------------
|
||||
// main :: () -> String
|
||||
const main = () => {
|
||||
const
|
||||
n = 5,
|
||||
cellWidth = 1 + `${pred(n ** 2)}`.length;
|
||||
|
||||
return unlines(
|
||||
spiral(n).map(
|
||||
row => (
|
||||
row.map(x => `${x}`
|
||||
.padStart(cellWidth, " "))
|
||||
)
|
||||
.join("")
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
// --------------------- GENERIC ---------------------
|
||||
|
||||
// enumFromTo :: Int -> Int -> [Int]
|
||||
const enumFromTo = m =>
|
||||
n => Array.from({
|
||||
length: 1 + n - m
|
||||
}, (_, i) => m + i);
|
||||
|
||||
|
||||
// pred :: Enum a => a -> a
|
||||
const pred = x => x - 1;
|
||||
|
||||
|
||||
// reverse :: [a] -> [a]
|
||||
const reverse = xs =>
|
||||
"string" === typeof xs ? (
|
||||
xs.split("").reverse()
|
||||
.join("")
|
||||
) : xs.slice(0).reverse();
|
||||
|
||||
|
||||
// transpose :: [[a]] -> [[a]]
|
||||
const transpose = rows =>
|
||||
// The columns of the input transposed
|
||||
// into new rows.
|
||||
// Simpler version of transpose, assuming input
|
||||
// rows of even length.
|
||||
Boolean(rows.length) ? rows[0].map(
|
||||
(_, i) => rows.flatMap(
|
||||
v => v[i]
|
||||
)
|
||||
) : [];
|
||||
|
||||
|
||||
// unlines :: [String] -> String
|
||||
const unlines = xs =>
|
||||
// A single string formed by the intercalation
|
||||
// of a list of strings with the newline character.
|
||||
xs.join("\n");
|
||||
|
||||
|
||||
// MAIN ---
|
||||
return main();
|
||||
})();
|
||||
26
Task/Spiral-matrix/Jq/spiral-matrix-1.jq
Normal file
26
Task/Spiral-matrix/Jq/spiral-matrix-1.jq
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
# Create an m x n matrix
|
||||
def matrix(m; n; init):
|
||||
if m == 0 then []
|
||||
elif m == 1 then [range(0;n)] | map(init)
|
||||
elif m > 0 then
|
||||
matrix(1;n;init) as $row
|
||||
| [range(0;m)] | map( $row )
|
||||
else error("matrix\(m);_;_) invalid")
|
||||
end ;
|
||||
|
||||
# Print a matrix neatly, each cell occupying n spaces
|
||||
def neatly(n):
|
||||
def right: tostring | ( " " * (n-length) + .);
|
||||
. as $in
|
||||
| length as $length
|
||||
| reduce range (0;$length) as $i
|
||||
(""; . + reduce range(0;$length) as $j
|
||||
(""; "\(.)\($in[$i][$j] | right )" ) + "\n" ) ;
|
||||
|
||||
def right:
|
||||
if . == [1, 0] then [ 0, -1]
|
||||
elif . == [0, -1] then [-1, 0]
|
||||
elif . == [-1, 0] then [ 0, 1]
|
||||
elif . == [0, 1] then [ 1, 0]
|
||||
else error("invalid direction: \(.)")
|
||||
end;
|
||||
14
Task/Spiral-matrix/Jq/spiral-matrix-2.jq
Normal file
14
Task/Spiral-matrix/Jq/spiral-matrix-2.jq
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
def spiral(n):
|
||||
# we just placed m at i,j, and we are moving in the direction d
|
||||
def _next(i; j; m; d):
|
||||
if m == (n*n) - 1 then .
|
||||
elif .[i+d[0]][j+d[1]] == false
|
||||
then .[i+d[0]][j+d[1]] = m+1 | _next(i+d[0]; j+d[1]; m+1; d)
|
||||
else (d|right) as $d
|
||||
| .[i+$d[0]][j+$d[1]] = m+1 | _next(i+$d[0]; j+$d[1]; m+1; $d)
|
||||
end;
|
||||
|
||||
matrix(n;n;false) | .[0][0] = 0 | _next(0;0;0; [0,1]) ;
|
||||
|
||||
# Example
|
||||
spiral(5) | neatly(3)
|
||||
43
Task/Spiral-matrix/Julia/spiral-matrix-1.julia
Normal file
43
Task/Spiral-matrix/Julia/spiral-matrix-1.julia
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
immutable Spiral
|
||||
m::Int
|
||||
n::Int
|
||||
cmax::Int
|
||||
dir::Array{Array{Int,1},1}
|
||||
bdelta::Array{Array{Int,1},1}
|
||||
end
|
||||
|
||||
function Spiral(m::Int, n::Int)
|
||||
cmax = m*n
|
||||
dir = Array{Int,1}[[0,1], [1,0], [0,-1], [-1,0]]
|
||||
bdelta = Array{Int,1}[[0,0,0,1], [-1,0,0,0],
|
||||
[0,-1,0,0], [0,0,1,0]]
|
||||
Spiral(m, n, cmax, dir, bdelta)
|
||||
end
|
||||
|
||||
function spiral(m::Int, n::Int)
|
||||
0<m&&0<n || error("The matrix dimensions must be positive.")
|
||||
Spiral(m, n)
|
||||
end
|
||||
spiral(n::Int) = spiral(n, n)
|
||||
|
||||
type SpState
|
||||
cnt::Int
|
||||
dirdex::Int
|
||||
cell::Array{Int,1}
|
||||
bounds::Array{Int,1}
|
||||
end
|
||||
|
||||
Base.length(sp::Spiral) = sp.cmax
|
||||
Base.start(sp::Spiral) = SpState(1, 1, [1,1], [sp.n,sp.m,1,1])
|
||||
Base.done(sp::Spiral, sps::SpState) = sps.cnt > sp.cmax
|
||||
|
||||
function Base.next(sp::Spiral, sps::SpState)
|
||||
s = sub2ind((sp.m, sp.n), sps.cell[1], sps.cell[2])
|
||||
if sps.cell[rem1(sps.dirdex+1, 2)] == sps.bounds[sps.dirdex]
|
||||
sps.bounds += sp.bdelta[sps.dirdex]
|
||||
sps.dirdex = rem1(sps.dirdex+1, 4)
|
||||
end
|
||||
sps.cell += sp.dir[sps.dirdex]
|
||||
sps.cnt += 1
|
||||
return (s, sps)
|
||||
end
|
||||
24
Task/Spiral-matrix/Julia/spiral-matrix-2.julia
Normal file
24
Task/Spiral-matrix/Julia/spiral-matrix-2.julia
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
using Formatting
|
||||
|
||||
function width{T<:Integer}(n::T)
|
||||
w = ndigits(n)
|
||||
n < 0 || return w
|
||||
return w + 1
|
||||
end
|
||||
|
||||
function pretty{T<:Integer}(a::Array{T,2}, indent::Int=4)
|
||||
lo, hi = extrema(a)
|
||||
w = max(width(lo), width(hi))
|
||||
id = " "^indent
|
||||
fe = FormatExpr(@sprintf(" {:%dd}", w))
|
||||
s = id
|
||||
nrow = size(a)[1]
|
||||
for i in 1:nrow
|
||||
for j in a[i,:]
|
||||
s *= format(fe, j)
|
||||
end
|
||||
i != nrow || continue
|
||||
s *= "\n"*id
|
||||
end
|
||||
return s
|
||||
end
|
||||
26
Task/Spiral-matrix/Julia/spiral-matrix-3.julia
Normal file
26
Task/Spiral-matrix/Julia/spiral-matrix-3.julia
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
n = 5
|
||||
println("The n = ", n, " spiral matrix:")
|
||||
a = zeros(Int, (n, n))
|
||||
for (i, s) in enumerate(spiral(n))
|
||||
a[s] = i-1
|
||||
end
|
||||
println(pretty(a))
|
||||
|
||||
m = 3
|
||||
println()
|
||||
println("Generalize to a non-square matrix (", m, "x", n, "):")
|
||||
a = zeros(Int, (m, n))
|
||||
for (i, s) in enumerate(spiral(m, n))
|
||||
a[s] = i-1
|
||||
end
|
||||
println(pretty(a))
|
||||
|
||||
p = primes(10^3)
|
||||
n = 7
|
||||
println()
|
||||
println("An n = ", n, " prime spiral matrix:")
|
||||
a = zeros(Int, (n, n))
|
||||
for (i, s) in enumerate(spiral(n))
|
||||
a[s] = p[i]
|
||||
end
|
||||
println(pretty(a))
|
||||
40
Task/Spiral-matrix/Kotlin/spiral-matrix.kotlin
Normal file
40
Task/Spiral-matrix/Kotlin/spiral-matrix.kotlin
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
// version 1.1.3
|
||||
|
||||
typealias Vector = IntArray
|
||||
typealias Matrix = Array<Vector>
|
||||
|
||||
fun spiralMatrix(n: Int): Matrix {
|
||||
val result = Matrix(n) { Vector(n) }
|
||||
var pos = 0
|
||||
var count = n
|
||||
var value = -n
|
||||
var sum = -1
|
||||
do {
|
||||
value = -value / n
|
||||
for (i in 0 until count) {
|
||||
sum += value
|
||||
result[sum / n][sum % n] = pos++
|
||||
}
|
||||
value *= n
|
||||
count--
|
||||
for (i in 0 until count) {
|
||||
sum += value
|
||||
result[sum / n][sum % n] = pos++
|
||||
}
|
||||
}
|
||||
while (count > 0)
|
||||
return result
|
||||
}
|
||||
|
||||
fun printMatrix(m: Matrix) {
|
||||
for (i in 0 until m.size) {
|
||||
for (j in 0 until m.size) print("%2d ".format(m[i][j]))
|
||||
println()
|
||||
}
|
||||
println()
|
||||
}
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
printMatrix(spiralMatrix(5))
|
||||
printMatrix(spiralMatrix(10))
|
||||
}
|
||||
76
Task/Spiral-matrix/Liberty-BASIC/spiral-matrix.basic
Normal file
76
Task/Spiral-matrix/Liberty-BASIC/spiral-matrix.basic
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
nomainwin
|
||||
|
||||
UpperLeftX = 50
|
||||
UpperLeftY = 50
|
||||
WindowWidth =900
|
||||
WindowHeight =930
|
||||
|
||||
statictext #w.st, "", 10, 850, 870, 40
|
||||
|
||||
open "Spiral matrix" for graphics_nsb_nf as #w
|
||||
|
||||
#w "trapclose [quit]"
|
||||
#w "backcolor darkblue; color cyan; fill darkblue"
|
||||
|
||||
for N =2 to 50
|
||||
|
||||
#w.st "!font courier_new "; int( 60 /N); " bold"
|
||||
#w "down; font arial "; int( 240 /N); " bold"
|
||||
|
||||
g$ ="ruld" ' direction sequence
|
||||
if N/2 =int( N/2) then pg =2 else pg =0 ' pointer to current direction
|
||||
' last move is left or right depending on N even/odd
|
||||
d$ =""
|
||||
|
||||
for i =1 to N -1 ' calculate direction to move
|
||||
d$ =nChar$( i, mid$( g$, pg +1, 1)) +d$
|
||||
pg =( pg +1) mod 4
|
||||
d$ =nChar$( i, mid$( g$, pg +1, 1)) +d$
|
||||
pg =( pg +1) mod 4
|
||||
next i
|
||||
|
||||
d$ =nChar$( N -1, "r") +d$ ' first row
|
||||
|
||||
#w.st " N ="; N; " "; d$
|
||||
|
||||
xp =60 +250 /N
|
||||
yp =80 +250 /N
|
||||
|
||||
stp =int( 750 /N)
|
||||
|
||||
for i =0 to N^2 -1
|
||||
dir$ =mid$( d$, i, 1)
|
||||
select case dir$
|
||||
case "r"
|
||||
xp =xp +stp
|
||||
case "d"
|
||||
yp =yp +stp
|
||||
case "l"
|
||||
xp =xp -stp
|
||||
case "u"
|
||||
yp =yp -stp
|
||||
end select
|
||||
|
||||
#w "place "; xp; " "; yp
|
||||
#w "\"; i
|
||||
next i
|
||||
|
||||
timer 3000, [on]
|
||||
wait
|
||||
[on]
|
||||
timer 0
|
||||
#w "cls"
|
||||
scan
|
||||
next N
|
||||
|
||||
wait
|
||||
|
||||
function nChar$( n, i$)
|
||||
for i =1 to n
|
||||
nChar$ =nChar$ +i$
|
||||
next i
|
||||
end function
|
||||
|
||||
[quit]
|
||||
close #w
|
||||
end
|
||||
19
Task/Spiral-matrix/Lua/spiral-matrix-1.lua
Normal file
19
Task/Spiral-matrix/Lua/spiral-matrix-1.lua
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
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
|
||||
local l = math.max(av(y), av(x))
|
||||
return (2*l-1)^2+4*l+2*l*sn(x+y)+sn(y^2-x^2)*(l-(av(y)==l and sn(y)*x or sn(x)*y)) -- OH GOD WHAT
|
||||
end
|
||||
|
||||
function spiralt(side)
|
||||
local ret, start, stop = {}, math.floor((-side+1)/2), math.floor((side-1)/2)
|
||||
for i = 1, side do
|
||||
ret[i] = {}
|
||||
for j = 1, side do
|
||||
ret[i][j] = side^2 - sindex(stop - i + 1,start + j - 1) --moves the coordinates so (0,0) is at the center of the spiral
|
||||
end
|
||||
end
|
||||
return ret
|
||||
end
|
||||
|
||||
for i,v in ipairs(spiralt(8)) do for j, u in ipairs(v) do io.write(u .. " ") end print() end
|
||||
13
Task/Spiral-matrix/Lua/spiral-matrix-2.lua
Normal file
13
Task/Spiral-matrix/Lua/spiral-matrix-2.lua
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
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)
|
||||
19
Task/Spiral-matrix/Lua/spiral-matrix-3.lua
Normal file
19
Task/Spiral-matrix/Lua/spiral-matrix-3.lua
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
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))
|
||||
11
Task/Spiral-matrix/MATLAB/spiral-matrix-1.m
Normal file
11
Task/Spiral-matrix/MATLAB/spiral-matrix-1.m
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
function matrix = reverseSpiral(n)
|
||||
|
||||
matrix = (-spiral(n))+n^2;
|
||||
|
||||
if mod(n,2)==0
|
||||
matrix = flipud(matrix);
|
||||
else
|
||||
matrix = fliplr(matrix);
|
||||
end
|
||||
|
||||
end %reverseSpiral
|
||||
9
Task/Spiral-matrix/MATLAB/spiral-matrix-2.m
Normal file
9
Task/Spiral-matrix/MATLAB/spiral-matrix-2.m
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
>> reverseSpiral(5)
|
||||
|
||||
ans =
|
||||
|
||||
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
|
||||
26
Task/Spiral-matrix/Maple/spiral-matrix.maple
Normal file
26
Task/Spiral-matrix/Maple/spiral-matrix.maple
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
with(ArrayTools):
|
||||
|
||||
spiralArray := proc(size::integer)
|
||||
local M, sideLength, count, i, j:
|
||||
M := Matrix(size):
|
||||
count := 0:
|
||||
sideLength := size:
|
||||
for i from 1 to ceil(sideLength / 2) do
|
||||
for j from 1 to sideLength do
|
||||
M[i,i + j - 1] := count++:
|
||||
end:
|
||||
for j from 1 to sideLength - 1 do
|
||||
M[i + j, sideLength + i - 1] := count++:
|
||||
end:
|
||||
for j from 1 to sideLength - 1 do
|
||||
M[i + sideLength - 1, sideLength - j + i - 1] := count++:
|
||||
end:
|
||||
for j from 1 to sideLength - 2 do
|
||||
M[sideLength + i - j - 1, i] := count++
|
||||
end:
|
||||
sideLength -= 2:
|
||||
end:
|
||||
return M;
|
||||
end proc:
|
||||
|
||||
spiralArray(5);
|
||||
16
Task/Spiral-matrix/Mathematica/spiral-matrix-1.math
Normal file
16
Task/Spiral-matrix/Mathematica/spiral-matrix-1.math
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
AddSquareRing[x_List/;Equal@@Dimensions[x] && Length[Dimensions[x]]==2]:=Module[{new=x,size,smallest},
|
||||
size=Length[x];
|
||||
smallest=x[[1,1]];
|
||||
Do[
|
||||
new[[i]]=Prepend[new[[i]],smallest-i];
|
||||
new[[i]]=Append[new[[i]],smallest-3 size+i-3]
|
||||
,{i,size}];
|
||||
PrependTo[new,Range[smallest-3size-3-size-1,smallest-3size-3]];
|
||||
AppendTo[new,Range[smallest-size-1,smallest-size-size-2,-1]];
|
||||
new
|
||||
]
|
||||
MakeSquareSpiral[size_Integer/;size>0]:=Module[{largest,start,times},
|
||||
start=size^2+If[Mod[size,2]==0,{{-4,-3},{-1,-2}},{{-1}}];
|
||||
times=If[Mod[size,2]==0,size/2-1,(size-1)/2];
|
||||
Nest[AddSquareRing,start,times]
|
||||
]
|
||||
2
Task/Spiral-matrix/Mathematica/spiral-matrix-2.math
Normal file
2
Task/Spiral-matrix/Mathematica/spiral-matrix-2.math
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
MakeSquareSpiral[2] // MatrixForm
|
||||
MakeSquareSpiral[7] // MatrixForm
|
||||
40
Task/Spiral-matrix/Maxima/spiral-matrix.maxima
Normal file
40
Task/Spiral-matrix/Maxima/spiral-matrix.maxima
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
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],
|
||||
vj: [0, 1, 0, -1],
|
||||
imin: 0,
|
||||
imax: n,
|
||||
jmin: 1,
|
||||
jmax: n + 1,
|
||||
p: 1,
|
||||
di: vi[p],
|
||||
dj: vj[p],
|
||||
i: 1,
|
||||
j: 1,
|
||||
for k from 1 thru n*n do (
|
||||
a[j, i]: k,
|
||||
i: i + di,
|
||||
j: j + dj,
|
||||
if i < imin or i > imax or j < jmin or j > jmax then (
|
||||
i: i - di,
|
||||
j: j - dj,
|
||||
p: mod(p, 4) + 1,
|
||||
di: vi[p],
|
||||
dj: vj[p],
|
||||
i: i + di,
|
||||
j: j + dj,
|
||||
if p = 1 then imax: imax - 1
|
||||
elseif p = 2 then jmax: jmax - 1
|
||||
elseif p = 3 then imin: imin + 1
|
||||
else jmin: jmin + 1
|
||||
)
|
||||
),
|
||||
a
|
||||
)$
|
||||
|
||||
spiral(5);
|
||||
/* matrix([ 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]) */
|
||||
8
Task/Spiral-matrix/MiniZinc/spiral-matrix.minizinc
Normal file
8
Task/Spiral-matrix/MiniZinc/spiral-matrix.minizinc
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
%Spiral Matrix. Nigel Galloway, February 3rd., 2020
|
||||
int: Size;
|
||||
array [1..Size,1..Size] of var 1..Size*Size: spiral;
|
||||
constraint spiral[1,1..]=1..Size;
|
||||
constraint forall(n in 2..(Size+1) div 2)(forall(g in n..Size+1-n)(spiral[n,g]=spiral[n,g-1]+1));
|
||||
constraint forall(n in 1..(Size+1) div 2)(forall(g in n+1..Size+1-n)(spiral[g,Size-n+1]=spiral[g-1,Size-n+1]+1));
|
||||
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)];
|
||||
91
Task/Spiral-matrix/NetRexx/spiral-matrix.netrexx
Normal file
91
Task/Spiral-matrix/NetRexx/spiral-matrix.netrexx
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
/* NetRexx */
|
||||
options replace format comments java crossref symbols binary
|
||||
|
||||
parse arg size .
|
||||
|
||||
if \size.datatype('W') then do
|
||||
printArray(generateArray(3))
|
||||
say
|
||||
printArray(generateArray(4))
|
||||
say
|
||||
printArray(generateArray(5))
|
||||
say
|
||||
end
|
||||
else do
|
||||
printArray(generateArray(size))
|
||||
say
|
||||
end
|
||||
|
||||
return
|
||||
|
||||
-- -----------------------------------------------------------------------------
|
||||
method generateArray(dimension = int) private static returns int[,]
|
||||
|
||||
-- the output array
|
||||
array = int[dimension, dimension]
|
||||
|
||||
-- get the number of squares, including the center one if
|
||||
-- the dimension is odd
|
||||
|
||||
squares = dimension % 2 + dimension // 2
|
||||
|
||||
-- length of a side for the current square
|
||||
sidelength = dimension
|
||||
current = 0
|
||||
|
||||
loop i_ = 0 to squares - 1
|
||||
|
||||
-- do each side of the current square
|
||||
-- top side
|
||||
loop j_ = 0 to sidelength - 1
|
||||
array[i_, i_ + j_] = current
|
||||
current = current + 1
|
||||
end j_
|
||||
|
||||
-- down the right side
|
||||
loop j_ = 1 to sidelength - 1
|
||||
array[i_ + j_, dimension - 1 - i_] = current
|
||||
current = current + 1
|
||||
end j_
|
||||
|
||||
-- across the bottom
|
||||
loop j_ = sidelength - 2 to 0 by -1
|
||||
array[dimension - 1 - i_, i_ + j_] = current
|
||||
current = current + 1
|
||||
end j_
|
||||
|
||||
-- and up the left side
|
||||
loop j_ = sidelength - 2 to 1 by -1
|
||||
array[i_ + j_, i_] = current
|
||||
current = current + 1
|
||||
end j_
|
||||
|
||||
-- reduce the length of the side by two rows
|
||||
sidelength = sidelength - 2
|
||||
end i_
|
||||
|
||||
return array
|
||||
|
||||
-- -----------------------------------------------------------------------------
|
||||
method printArray(array = int[,]) private static
|
||||
|
||||
dimension = array[1].length
|
||||
rl = formatSize(array)
|
||||
loop i_ = 0 to dimension - 1
|
||||
line = Rexx("|")
|
||||
loop j_ = 0 to dimension - 1
|
||||
line = line Rexx(array[i_, j_]).right(rl)
|
||||
end j_
|
||||
line = line "|"
|
||||
say line
|
||||
end i_
|
||||
|
||||
return
|
||||
|
||||
-- -----------------------------------------------------------------------------
|
||||
method formatSize(array = int[,]) private static returns Rexx
|
||||
|
||||
dim = array[1].length
|
||||
maxNum = Rexx(dim * dim - 1).length()
|
||||
|
||||
return maxNum
|
||||
27
Task/Spiral-matrix/Nim/spiral-matrix.nim
Normal file
27
Task/Spiral-matrix/Nim/spiral-matrix.nim
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import sequtils, strutils
|
||||
|
||||
proc `$`(m: seq[seq[int]]): string =
|
||||
for r in m:
|
||||
let lg = result.len
|
||||
for c in r:
|
||||
result.addSep(" ", lg)
|
||||
result.add align($c, 2)
|
||||
result.add '\n'
|
||||
|
||||
proc spiral(n: Positive): seq[seq[int]] =
|
||||
result = newSeqWith(n, repeat(-1, n))
|
||||
var dx = 1
|
||||
var dy, x, y = 0
|
||||
for i in 0 ..< (n * n):
|
||||
result[y][x] = i
|
||||
let (nx, ny) = (x+dx, y+dy)
|
||||
if nx in 0 ..< n and ny in 0 ..< n and result[ny][nx] == -1:
|
||||
x = nx
|
||||
y = ny
|
||||
else:
|
||||
swap dx, dy
|
||||
dx = -dx
|
||||
x += dx
|
||||
y += dy
|
||||
|
||||
echo spiral(5)
|
||||
39
Task/Spiral-matrix/OCaml/spiral-matrix-1.ocaml
Normal file
39
Task/Spiral-matrix/OCaml/spiral-matrix-1.ocaml
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
let next_dir = function
|
||||
| 1, 0 -> 0, -1
|
||||
| 0, 1 -> 1, 0
|
||||
| -1, 0 -> 0, 1
|
||||
| 0, -1 -> -1, 0
|
||||
| _ -> assert false
|
||||
|
||||
let next_pos ~pos:(x,y) ~dir:(nx,ny) = (x+nx, y+ny)
|
||||
|
||||
let next_cell ar ~pos:(x,y) ~dir:(nx,ny) =
|
||||
try ar.(x+nx).(y+ny)
|
||||
with _ -> -2
|
||||
|
||||
let for_loop n init fn =
|
||||
let rec aux i v =
|
||||
if i < n then aux (i+1) (fn i v)
|
||||
in
|
||||
aux 0 init
|
||||
|
||||
let spiral ~n =
|
||||
let ar = Array.make_matrix n n (-1) in
|
||||
let pos = 0, 0 in
|
||||
let dir = 0, 1 in
|
||||
let set (x, y) i = ar.(x).(y) <- i in
|
||||
let step (pos, dir) =
|
||||
match next_cell ar pos dir with
|
||||
| -1 -> (next_pos pos dir, dir)
|
||||
| _ -> let dir = next_dir dir in (next_pos pos dir, dir)
|
||||
in
|
||||
for_loop (n*n) (pos, dir)
|
||||
(fun i (pos, dir) -> set pos i; step (pos, dir));
|
||||
(ar)
|
||||
|
||||
let print =
|
||||
Array.iter (fun line ->
|
||||
Array.iter (Printf.printf " %2d") line;
|
||||
print_newline())
|
||||
|
||||
let () = print(spiral 5)
|
||||
17
Task/Spiral-matrix/OCaml/spiral-matrix-2.ocaml
Normal file
17
Task/Spiral-matrix/OCaml/spiral-matrix-2.ocaml
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
let spiral n =
|
||||
let ar = Array.make_matrix n n (-1) in
|
||||
let out i = i < 0 || i >= n in
|
||||
let too_far (x,y) = out x || out y || ar.(x).(y) >= 0 in
|
||||
let step x y (dx,dy) = (x+dx,y+dy) in
|
||||
let turn (i,j) = (j,-i) in
|
||||
let rec iter (x,y) d i =
|
||||
ar.(x).(y) <- i;
|
||||
if i < n*n-1 then
|
||||
let d' = if too_far (step x y d) then turn d else d in
|
||||
iter (step x y d') d' (i+1) in
|
||||
(iter (0,0) (0,1) 0; ar)
|
||||
|
||||
let show =
|
||||
Array.iter (fun v -> Array.iter (Printf.printf " %2d") v; print_newline())
|
||||
|
||||
let _ = show (spiral 5)
|
||||
21
Task/Spiral-matrix/Octave/spiral-matrix.octave
Normal file
21
Task/Spiral-matrix/Octave/spiral-matrix.octave
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
function a = spiral(n)
|
||||
a = ones(n*n, 1);
|
||||
u = -(i = n) * (v = ones(n, 1));
|
||||
for k = n-1:-1:1
|
||||
j = 1:k;
|
||||
a(j+i) = u(j) = -u(j);
|
||||
a(j+(i+k)) = v(j) = -v(j);
|
||||
i += 2*k;
|
||||
endfor
|
||||
a(cumsum(a)) = 1:n*n;
|
||||
a = reshape(a, n, n)'-1;
|
||||
endfunction
|
||||
|
||||
>> spiral(5)
|
||||
ans =
|
||||
|
||||
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
|
||||
55
Task/Spiral-matrix/OoRexx/spiral-matrix.rexx
Normal file
55
Task/Spiral-matrix/OoRexx/spiral-matrix.rexx
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
call printArray generateArray(3)
|
||||
say
|
||||
call printArray generateArray(4)
|
||||
say
|
||||
call printArray generateArray(5)
|
||||
|
||||
::routine generateArray
|
||||
use arg dimension
|
||||
-- the output array
|
||||
array = .array~new(dimension, dimension)
|
||||
|
||||
-- get the number of squares, including the center one if
|
||||
-- the dimension is odd
|
||||
squares = dimension % 2 + dimension // 2
|
||||
-- length of a side for the current square
|
||||
sidelength = dimension
|
||||
current = 0
|
||||
loop i = 1 to squares
|
||||
-- do each side of the current square
|
||||
-- top side
|
||||
loop j = 0 to sidelength - 1
|
||||
array[i, i + j] = current
|
||||
current += 1
|
||||
end
|
||||
-- down the right side
|
||||
loop j = 1 to sidelength - 1
|
||||
array[i + j, dimension - i + 1] = current
|
||||
current += 1
|
||||
end
|
||||
-- across the bottom
|
||||
loop j = sidelength - 2 to 0 by -1
|
||||
array[dimension - i + 1, i + j] = current
|
||||
current += 1
|
||||
end
|
||||
-- and up the left side
|
||||
loop j = sidelength - 2 to 1 by -1
|
||||
array[i + j, i] = current
|
||||
current += 1
|
||||
end
|
||||
-- reduce the length of the side by two rows
|
||||
sidelength -= 2
|
||||
end
|
||||
return array
|
||||
|
||||
::routine printArray
|
||||
use arg array
|
||||
dimension = array~dimension(1)
|
||||
loop i = 1 to dimension
|
||||
line = "|"
|
||||
loop j = 1 to dimension
|
||||
line = line array[i, j]~right(2)
|
||||
end
|
||||
line = line "|"
|
||||
say line
|
||||
end
|
||||
42
Task/Spiral-matrix/Oz/spiral-matrix.oz
Normal file
42
Task/Spiral-matrix/Oz/spiral-matrix.oz
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
declare
|
||||
fun {Spiral N}
|
||||
%% create nested array
|
||||
Arr = {Array.new 1 N unit}
|
||||
for Y in 1..N do Arr.Y := {Array.new 1 N 0} end
|
||||
%% fill it recursively with increasing numbers
|
||||
C = {Counter 0}
|
||||
in
|
||||
{Fill Arr 1 N C}
|
||||
Arr
|
||||
end
|
||||
|
||||
proc {Fill Arr S E C}
|
||||
%% go right
|
||||
for X in S..E do
|
||||
Arr.S.X := {C}
|
||||
end
|
||||
%% go down
|
||||
for Y in S+1..E do
|
||||
Arr.Y.E := {C}
|
||||
end
|
||||
%% go left
|
||||
for X in E-1..S;~1 do
|
||||
Arr.E.X := {C}
|
||||
end
|
||||
%% go up
|
||||
for Y in E-1..S+1;~1 do
|
||||
Arr.Y.S := {C}
|
||||
end
|
||||
%% fill the inner rectangle
|
||||
if E - S > 1 then {Fill Arr S+1 E-1 C} end
|
||||
end
|
||||
|
||||
fun {Counter N}
|
||||
C = {NewCell N}
|
||||
in
|
||||
fun {$}
|
||||
C := @C + 1
|
||||
end
|
||||
end
|
||||
in
|
||||
{Inspect {Spiral 5}}
|
||||
9
Task/Spiral-matrix/PARI-GP/spiral-matrix.parigp
Normal file
9
Task/Spiral-matrix/PARI-GP/spiral-matrix.parigp
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
spiral(dim) = {
|
||||
my (M = matrix(dim, dim), p = s = 1, q = i = 0);
|
||||
for (n=1, dim,
|
||||
for (b=1, dim-n+1, M[p,q+=s] = i; i++);
|
||||
for (b=1, dim-n, M[p+=s,q] = i; i++);
|
||||
s = -s;
|
||||
);
|
||||
M
|
||||
}
|
||||
55
Task/Spiral-matrix/PL-I/spiral-matrix.pli
Normal file
55
Task/Spiral-matrix/PL-I/spiral-matrix.pli
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
/* 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. */
|
||||
declare n fixed binary;
|
||||
|
||||
put skip list ('Please type the size of the square:');
|
||||
get list (n);
|
||||
|
||||
begin;
|
||||
declare A(n,n) fixed binary;
|
||||
declare (i, j, iinc, jinc, q) fixed binary;
|
||||
|
||||
A = -1;
|
||||
|
||||
i, j = 1; iinc = 0; jinc = 1;
|
||||
do q = 0 to n**2-1;
|
||||
if a(i,j) < 0 then
|
||||
a(i,j) = q;
|
||||
else
|
||||
do;
|
||||
/* back up */
|
||||
j = j -jinc; i = i - iinc;
|
||||
/* change direction */
|
||||
if iinc = 0 & jinc = 1 then do; iinc = 1; jinc = 0; end;
|
||||
else if iinc = 1 & jinc = 0 then do; iinc = 0; jinc = -1; end;
|
||||
else if iinc = 0 & jinc = -1 then do; iinc = -1; jinc = 0; end;
|
||||
else if iinc = -1 & jinc = 0 then do; iinc = 0; jinc = 1; end;
|
||||
/* Take one step in the new direction */
|
||||
i = i + iinc; j = j + jinc;
|
||||
a(i,j) = q;
|
||||
end;
|
||||
if i+iinc > n | i+iinc < 1 then
|
||||
do;
|
||||
iinc = 0; jinc = 1;
|
||||
if j+1 > n then jinc = -1; else if j-1 < 1 then jinc = 1;
|
||||
if a(i+iinc,j+jinc) >= 0 then jinc = -jinc;
|
||||
/* j = j + jinc; /* to move on from the present (filled) position */
|
||||
end;
|
||||
else i = i + iinc;
|
||||
if j+jinc > n | j+jinc < 1 then
|
||||
do;
|
||||
jinc = 0; iinc = 1;
|
||||
if i+1 > n then iinc = -1; else if i-1 < 1 then iinc = 1;
|
||||
if a(i+iinc,j+jinc) >= 0 then iinc = -iinc;
|
||||
i = i + iinc; /* to move on from the present (filled) position */
|
||||
end;
|
||||
else j = j + jinc;
|
||||
end;
|
||||
|
||||
/* Display the square. */
|
||||
do i = 1 to n;
|
||||
put skip edit (A(i,*)) (F(4));
|
||||
end;
|
||||
|
||||
end;
|
||||
70
Task/Spiral-matrix/Pascal/spiral-matrix.pas
Normal file
70
Task/Spiral-matrix/Pascal/spiral-matrix.pas
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
program Spiralmat;
|
||||
type
|
||||
tDir = (left,down,right,up);
|
||||
tdxy = record
|
||||
dx,dy: longint;
|
||||
end;
|
||||
tdeltaDir = array[tDir] of tdxy;
|
||||
const
|
||||
Nextdir : array[tDir] of tDir = (down,right,up,left);
|
||||
cDir : tDeltaDir = ((dx:1;dy:0),(dx:0;dy:1),(dx:-1;dy:0),(dx:0;dy:-1));
|
||||
cMaxN = 32;
|
||||
type
|
||||
tSpiral = array[0..cMaxN,0..cMaxN] of LongInt;
|
||||
|
||||
function FillSpiral(n:longint):tSpiral;
|
||||
var
|
||||
b,i,k, dn,x,y : longInt;
|
||||
dir : tDir;
|
||||
tmpSp : tSpiral;
|
||||
BEGIN
|
||||
b := 0;
|
||||
x := 0;
|
||||
y := 0;
|
||||
//only for the first line
|
||||
k := -1;
|
||||
dn := n-1;
|
||||
tmpSp[x,y] := b;
|
||||
dir := left;
|
||||
repeat
|
||||
i := 0;
|
||||
while i < dn do
|
||||
begin
|
||||
inc(b);
|
||||
tmpSp[x,y] := b;
|
||||
inc(x,cDir[dir].dx);
|
||||
inc(y,cDir[dir].dy);
|
||||
inc(i);
|
||||
end;
|
||||
Dir:= NextDir[dir];
|
||||
inc(k);
|
||||
IF k > 1 then
|
||||
begin
|
||||
k := 0;
|
||||
//shorten the line every second direction change
|
||||
dn := dn-1;
|
||||
if dn <= 0 then
|
||||
BREAK;
|
||||
end;
|
||||
until false;
|
||||
//the last
|
||||
tmpSp[x,y] := b+1;
|
||||
FillSpiral := tmpSp;
|
||||
end;
|
||||
|
||||
var
|
||||
a : tSpiral;
|
||||
x,y,n : LongInt;
|
||||
BEGIN
|
||||
For n := 1 to 5{cMaxN} do
|
||||
begin
|
||||
A:=FillSpiral(n);
|
||||
For y := 0 to n-1 do
|
||||
begin
|
||||
For x := 0 to n-1 do
|
||||
write(A[x,y]:4);
|
||||
writeln;
|
||||
end;
|
||||
writeln;
|
||||
end;
|
||||
END.
|
||||
21
Task/Spiral-matrix/Perl/spiral-matrix.pl
Normal file
21
Task/Spiral-matrix/Perl/spiral-matrix.pl
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
sub spiral
|
||||
{my ($n, $x, $y, $dx, $dy, @a) = (shift, 0, 0, 1, 0);
|
||||
foreach (0 .. $n**2 - 1)
|
||||
{$a[$y][$x] = $_;
|
||||
my ($nx, $ny) = ($x + $dx, $y + $dy);
|
||||
($dx, $dy) =
|
||||
$dx == 1 && ($nx == $n || defined $a[$ny][$nx])
|
||||
? ( 0, 1)
|
||||
: $dy == 1 && ($ny == $n || defined $a[$ny][$nx])
|
||||
? (-1, 0)
|
||||
: $dx == -1 && ($nx < 0 || defined $a[$ny][$nx])
|
||||
? ( 0, -1)
|
||||
: $dy == -1 && ($ny < 0 || defined $a[$ny][$nx])
|
||||
? ( 1, 0)
|
||||
: ($dx, $dy);
|
||||
($x, $y) = ($x + $dx, $y + $dy);}
|
||||
return @a;}
|
||||
|
||||
foreach (spiral 5)
|
||||
{printf "%3d", $_ foreach @$_;
|
||||
print "\n";}
|
||||
19
Task/Spiral-matrix/Phix/spiral-matrix.phix
Normal file
19
Task/Spiral-matrix/Phix/spiral-matrix.phix
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
(phixonline)-->
|
||||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
<span style="color: #000000;">x</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">dx</span>
|
||||
<span style="color: #000000;">y</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">dy</span>
|
||||
<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>
|
||||
<span style="color: #000000;">counter</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
|
||||
<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>
|
||||
<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>
|
||||
|
||||
<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>
|
||||
<!--
|
||||
19
Task/Spiral-matrix/PicoLisp/spiral-matrix.l
Normal file
19
Task/Spiral-matrix/PicoLisp/spiral-matrix.l
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
(load "@lib/simul.l")
|
||||
|
||||
(de spiral (N)
|
||||
(prog1 (grid N N)
|
||||
(let (Dir '(north east south west .) This 'a1)
|
||||
(for Val (* N N)
|
||||
(=: val Val)
|
||||
(setq This
|
||||
(or
|
||||
(with ((car Dir) This)
|
||||
(unless (: val) This) )
|
||||
(with ((car (setq Dir (cdr Dir))) This)
|
||||
(unless (: val) This) ) ) ) ) ) ) )
|
||||
|
||||
(mapc
|
||||
'((L)
|
||||
(for This L (prin (align 3 (: val))))
|
||||
(prinl) )
|
||||
(spiral 5) )
|
||||
36
Task/Spiral-matrix/PowerShell/spiral-matrix.psh
Normal file
36
Task/Spiral-matrix/PowerShell/spiral-matrix.psh
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
function Spiral-Matrix ( [int]$N )
|
||||
{
|
||||
# Initialize variables
|
||||
$X = 0
|
||||
$Y = -1
|
||||
$i = 0
|
||||
$Sign = 1
|
||||
|
||||
# Intialize array
|
||||
$A = New-Object 'int[,]' $N, $N
|
||||
|
||||
# Set top row
|
||||
1..$N | ForEach { $Y += $Sign; $A[$X,$Y] = ++$i }
|
||||
|
||||
# For each remaining half spiral...
|
||||
ForEach ( $M in ($N-1)..1 )
|
||||
{
|
||||
# Set the vertical quarter spiral
|
||||
1..$M | ForEach { $X += $Sign; $A[$X,$Y] = ++$i }
|
||||
|
||||
# Curve the spiral
|
||||
$Sign = -$Sign
|
||||
|
||||
# Set the horizontal quarter spiral
|
||||
1..$M | ForEach { $Y += $Sign; $A[$X,$Y] = ++$i }
|
||||
}
|
||||
|
||||
# Convert the array to text output
|
||||
$Spiral = ForEach ( $X in 1..$N ) { ( 1..$N | ForEach { $A[($X-1),($_-1)] } ) -join "`t" }
|
||||
|
||||
return $Spiral
|
||||
}
|
||||
|
||||
Spiral-Matrix 5
|
||||
""
|
||||
Spiral-Matrix 7
|
||||
51
Task/Spiral-matrix/Prolog/spiral-matrix.pro
Normal file
51
Task/Spiral-matrix/Prolog/spiral-matrix.pro
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
% Prolog implementation: SWI-Prolog 7.2.3
|
||||
|
||||
replace([_|T], 0, E, [E|T]) :- !.
|
||||
replace([H|T], N, E, Xs) :-
|
||||
succ(N1, N), replace(T, N1, E, Xs1), Xs = [H|Xs1].
|
||||
|
||||
% True if Xs is the Original grid with the element at (X, Y) replaces by E.
|
||||
replace_in([H|T], (0, Y), E, Xs) :- replace(H, Y, E, NH), Xs = [NH|T], !.
|
||||
replace_in([H|T], (X, Y), E, Xs) :-
|
||||
succ(X1, X), replace_in(T, (X1, Y), E, Xs1), Xs = [H|Xs1].
|
||||
|
||||
% True, if E is the value at (X, Y) in Xs
|
||||
get_in(Xs, (X, Y), E) :- nth0(X, Xs, L), nth0(Y, L, E).
|
||||
|
||||
create(N, Mx) :- % NxN grid full of nils
|
||||
numlist(1, N, Ns),
|
||||
findall(X, (member(_, Ns), X = nil), Ls),
|
||||
findall(X, (member(_, Ns), X = Ls), Mx).
|
||||
|
||||
% Depending of the direction, returns two possible coordinates and directions
|
||||
% (C,D) that will be used in case of a turn, and (A,B) otherwise.
|
||||
ops(right, (X,Y), (A,B), (C,D), D1, D2) :-
|
||||
A is X, B is Y+1, D1 = right, C is X+1, D is Y, D2 = down.
|
||||
|
||||
ops(left, (X,Y), (A,B), (C,D), D1, D2) :-
|
||||
A is X, B is Y-1, D1 = left, C is X-1, D is Y, D2 = up.
|
||||
|
||||
ops(up, (X,Y), (A,B), (C,D), D1, D2) :-
|
||||
A is X-1, B is Y, D1 = up, C is X, D is Y+1, D2 = right.
|
||||
|
||||
ops(down, (X,Y), (A,B), (C,D), D1, D2) :-
|
||||
A is X+1, B is Y, D1 = down, C is X, D is Y-1, D2 = left.
|
||||
|
||||
% True if NCoor is the right coor in spiral shape. Returns a new direction also.
|
||||
next(Dir, Mx, Coor, NCoor, NDir) :-
|
||||
ops(Dir, Coor, C1, C2, D1, D2),
|
||||
(get_in(Mx, C1, nil) -> NCoor = C1, NDir = D1
|
||||
; NCoor = C2, NDir = D2).
|
||||
|
||||
% Returns an spiral with [H|Vs] elements called R, only work if the length of
|
||||
% [H|Vs], is the square of the size of the grid.
|
||||
spiralH(Dir, Mx, Coor, [H|Vs], R) :-
|
||||
replace_in(Mx, Coor, H, NMx),
|
||||
(Vs = [] -> R = NMx
|
||||
; next(Dir, Mx, Coor, NCoor, NDir),
|
||||
spiralH(NDir, NMx, NCoor, Vs, R)).
|
||||
|
||||
% True if Mx is the grid in spiral shape of the numbers from 0 to N*N-1.
|
||||
spiral(N, Mx) :-
|
||||
Sq is N*N-1, numlist(0, Sq, Ns),
|
||||
create(N, EMx), spiralH(right, EMx, (0,0), Ns, Mx).
|
||||
57
Task/Spiral-matrix/PureBasic/spiral-matrix.basic
Normal file
57
Task/Spiral-matrix/PureBasic/spiral-matrix.basic
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
Procedure spiralMatrix(size = 1)
|
||||
Protected i, x = -1, y, count = size, n
|
||||
Dim a(size - 1,size - 1)
|
||||
|
||||
For i = 1 To count
|
||||
x + 1
|
||||
a(x,y) = n
|
||||
n + 1
|
||||
Next
|
||||
|
||||
Repeat
|
||||
count - 1
|
||||
For i = 1 To count
|
||||
y + 1
|
||||
a(x,y) = n
|
||||
n + 1
|
||||
Next
|
||||
For i = 1 To count
|
||||
x - 1
|
||||
a(x,y) = n
|
||||
n + 1
|
||||
Next
|
||||
|
||||
count - 1
|
||||
For i = 1 To count
|
||||
y - 1
|
||||
a(x,y) = n
|
||||
n + 1
|
||||
Next
|
||||
For i = 1 To count
|
||||
x + 1
|
||||
a(x,y) = n
|
||||
n + 1
|
||||
Next
|
||||
Until count < 1
|
||||
|
||||
PrintN("Spiral: " + Str(Size) + #CRLF$)
|
||||
Protected colWidth = Len(Str(size * size - 1)) + 1
|
||||
For y = 0 To size - 1
|
||||
For x = 0 To size - 1
|
||||
Print("" + LSet(Str(a(x, y)), colWidth, " ") + "")
|
||||
Next
|
||||
PrintN("")
|
||||
Next
|
||||
PrintN("")
|
||||
EndProcedure
|
||||
|
||||
If OpenConsole()
|
||||
spiralMatrix(2)
|
||||
PrintN("")
|
||||
spiralMatrix(5)
|
||||
|
||||
|
||||
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
|
||||
Input()
|
||||
CloseConsole()
|
||||
EndIf
|
||||
22
Task/Spiral-matrix/Python/spiral-matrix-1.py
Normal file
22
Task/Spiral-matrix/Python/spiral-matrix-1.py
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
def spiral(n):
|
||||
dx,dy = 1,0 # Starting increments
|
||||
x,y = 0,0 # Starting location
|
||||
myarray = [[None]* n for j in range(n)]
|
||||
for i in xrange(n**2):
|
||||
myarray[x][y] = i
|
||||
nx,ny = x+dx, y+dy
|
||||
if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None:
|
||||
x,y = nx,ny
|
||||
else:
|
||||
dx,dy = -dy,dx
|
||||
x,y = x+dx, y+dy
|
||||
return myarray
|
||||
|
||||
def printspiral(myarray):
|
||||
n = range(len(myarray))
|
||||
for y in n:
|
||||
for x in n:
|
||||
print "%2i" % myarray[x][y],
|
||||
print
|
||||
|
||||
printspiral(spiral(5))
|
||||
23
Task/Spiral-matrix/Python/spiral-matrix-2.py
Normal file
23
Task/Spiral-matrix/Python/spiral-matrix-2.py
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
def spiral(n):
|
||||
def spiral_part(x, y, n):
|
||||
if x == -1 and y == 0:
|
||||
return -1
|
||||
if y == (x+1) and x < (n // 2):
|
||||
return spiral_part(x-1, y-1, n-1) + 4*(n-y)
|
||||
if x < (n-y) and y <= x:
|
||||
return spiral_part(y-1, y, n) + (x-y) + 1
|
||||
if x >= (n-y) and y <= x:
|
||||
return spiral_part(x, y-1, n) + 1
|
||||
if x >= (n-y) and y > x:
|
||||
return spiral_part(x+1, y, n) + 1
|
||||
if x < (n-y) and y > x:
|
||||
return spiral_part(x, y-1, n) - 1
|
||||
|
||||
array = [[0] * n for j in xrange(n)]
|
||||
for x in xrange(n):
|
||||
for y in xrange(n):
|
||||
array[x][y] = spiral_part(y, x, n)
|
||||
return array
|
||||
|
||||
for row in spiral(5):
|
||||
print " ".join("%2s" % x for x in row)
|
||||
18
Task/Spiral-matrix/Python/spiral-matrix-3.py
Normal file
18
Task/Spiral-matrix/Python/spiral-matrix-3.py
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
def rot_right(a):
|
||||
return zip(*a[::-1])
|
||||
|
||||
def sp(m, n, start = 0):
|
||||
""" Generate number range spiral of dimensions m x n
|
||||
"""
|
||||
if n == 0:
|
||||
yield ()
|
||||
else:
|
||||
yield tuple(range(start, m + start))
|
||||
for row in rot_right(list(sp(n - 1, m, m + start))):
|
||||
yield row
|
||||
|
||||
def spiral(m):
|
||||
return sp(m, m)
|
||||
|
||||
for row in spiral(5):
|
||||
print(''.join('%3i' % i for i in row))
|
||||
16
Task/Spiral-matrix/Python/spiral-matrix-4.py
Normal file
16
Task/Spiral-matrix/Python/spiral-matrix-4.py
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
def spiral(n):
|
||||
dat = [[None] * n for i in range(n)]
|
||||
le = [[i + 1, i + 1] for i in reversed(range(n))]
|
||||
le = sum(le, [])[1:] # for n = 5 le will be [5, 4, 4, 3, 3, 2, 2, 1, 1]
|
||||
dxdy = [[1, 0], [0, 1], [-1, 0], [0, -1]] * ((len(le) + 4) / 4) # long enough
|
||||
x, y, val = -1, 0, -1
|
||||
for steps, (dx, dy) in zip(le, dxdy):
|
||||
x, y, val = x + dx, y + dy, val + 1
|
||||
for j in range(steps):
|
||||
dat[y][x] = val
|
||||
if j != steps-1:
|
||||
x, y, val = x + dx, y + dy, val + 1
|
||||
return dat
|
||||
|
||||
for row in spiral(5): # calc spiral and print it
|
||||
print ' '.join('%3s' % x for x in row)
|
||||
19
Task/Spiral-matrix/Python/spiral-matrix-5.py
Normal file
19
Task/Spiral-matrix/Python/spiral-matrix-5.py
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import itertools
|
||||
|
||||
concat = itertools.chain.from_iterable
|
||||
def partial_sums(items):
|
||||
s = 0
|
||||
for x in items:
|
||||
s += x
|
||||
yield s
|
||||
|
||||
grade = lambda xs: sorted(range(len(xs)), key=xs.__getitem__)
|
||||
values = lambda n: itertools.cycle([1,n,-1,-n])
|
||||
counts = lambda n: concat([i,i-1] for i in range(n,0,-1))
|
||||
reshape = lambda n, xs: zip(*([iter(xs)] * n))
|
||||
|
||||
spiral = lambda n: reshape(n, grade(list(partial_sums(concat(
|
||||
[v]*c for c,v in zip(counts(n), values(n)))))))
|
||||
|
||||
for row in spiral(5):
|
||||
print(' '.join('%3s' % x for x in row))
|
||||
43
Task/Spiral-matrix/Python/spiral-matrix-6.py
Normal file
43
Task/Spiral-matrix/Python/spiral-matrix-6.py
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
'''Spiral Matrix'''
|
||||
|
||||
|
||||
# spiral :: Int -> [[Int]]
|
||||
def spiral(n):
|
||||
'''The rows of a spiral matrix of order N.
|
||||
'''
|
||||
def go(rows, cols, x):
|
||||
return [range(x, x + cols)] + [
|
||||
reversed(x) for x
|
||||
in zip(*go(cols, rows - 1, x + cols))
|
||||
] if 0 < rows else [[]]
|
||||
return go(n, n, 0)
|
||||
|
||||
|
||||
# ------------------------- TEST -------------------------
|
||||
# main :: IO ()
|
||||
def main():
|
||||
'''Spiral matrix of order 5, in wiki table markup.
|
||||
'''
|
||||
print(
|
||||
wikiTable(spiral(5))
|
||||
)
|
||||
|
||||
|
||||
# ---------------------- FORMATTING ----------------------
|
||||
|
||||
# wikiTable :: [[a]] -> String
|
||||
def wikiTable(rows):
|
||||
'''Wiki markup for a no-frills tabulation of rows.'''
|
||||
return '{| class="wikitable" style="' + (
|
||||
'width:12em;height:12em;table-layout:fixed;"|-\n'
|
||||
) + '\n|-\n'.join(
|
||||
'| ' + ' || '.join(
|
||||
str(cell) for cell in row
|
||||
)
|
||||
for row in rows
|
||||
) + '\n|}'
|
||||
|
||||
|
||||
# MAIN ---
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
12
Task/Spiral-matrix/Python/spiral-matrix-7.py
Normal file
12
Task/Spiral-matrix/Python/spiral-matrix-7.py
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
def spiral_matrix(n):
|
||||
m = [[0] * n for i in range(n)]
|
||||
dx, dy = [0, 1, 0, -1], [1, 0, -1, 0]
|
||||
x, y, c = 0, -1, 1
|
||||
for i in range(n + n - 1):
|
||||
for j in range((n + n - i) // 2):
|
||||
x += dx[i % 4]
|
||||
y += dy[i % 4]
|
||||
m[x][y] = c
|
||||
c += 1
|
||||
return m
|
||||
for i in spiral_matrix(5): print(*i)
|
||||
5
Task/Spiral-matrix/Python/spiral-matrix-8.py
Normal file
5
Task/Spiral-matrix/Python/spiral-matrix-8.py
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
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
|
||||
47
Task/Spiral-matrix/Quackery/spiral-matrix.quackery
Normal file
47
Task/Spiral-matrix/Quackery/spiral-matrix.quackery
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
[ stack ] is stepcount ( --> s )
|
||||
[ stack ] is position ( --> s )
|
||||
[ stack ] is heading ( --> s )
|
||||
|
||||
[ heading take
|
||||
behead join
|
||||
heading put ] is right ( --> )
|
||||
|
||||
[ heading share 0 peek
|
||||
unrot times
|
||||
[ position share
|
||||
stepcount share
|
||||
unrot poke
|
||||
over position tally
|
||||
1 stepcount tally ]
|
||||
nip ] is walk ( [ n --> [ )
|
||||
|
||||
[ dip [ temp put [] ]
|
||||
temp share times
|
||||
[ temp share split
|
||||
dip
|
||||
[ nested join ] ]
|
||||
drop temp release ] is matrixify ( n [ --> [ )
|
||||
|
||||
[ 0 stepcount put ( set up... )
|
||||
0 position put
|
||||
' [ 1 ] over join
|
||||
-1 join over negate join
|
||||
heading put
|
||||
0 over dup * of
|
||||
|
||||
over 1 - walk right ( turtle draws spiral )
|
||||
over 1 - times
|
||||
[ i 1+ walk right
|
||||
i 1+ walk right ]
|
||||
1 walk
|
||||
|
||||
matrixify ( ...tidy up )
|
||||
heading release
|
||||
position release
|
||||
stepcount release ] is spiral ( n --> [ )
|
||||
|
||||
9 spiral
|
||||
witheach
|
||||
[ witheach
|
||||
[ dup 10 < if sp echo sp ]
|
||||
cr ]
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue