Zig-zag matrix: Difference between revisions
m
→{{header|RPL}}: typo
(+Maple) |
m (→{{header|RPL}}: typo) |
||
(38 intermediate revisions by 23 users not shown) | |||
Line 23:
;Related tasks:
* [[Spiral matrix]]
* [[
* [[
Line 30:
* Wiktionary entry: [https://en.wiktionary.org/wiki/antidiagonal anti-diagonals]
<br><br>
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">F zigzag(n)
F compare(xy)
V (x, y) = xy
R (x + y, I (x + y) % 2 {-y} E y)
V xs = 0 .< n
R Dict(enumerate(sorted((multiloop(xs, xs, (x, y) -> (x, y))), key' compare)), (n, index) -> (index, n))
F printzz(myarray)
V n = Int(myarray.len ^ 0.5 + 0.5)
V xs = 0 .< n
print((xs.map(y -> @xs.map(x -> ‘#3’.format(@@myarray[(x, @y)])).join(‘’))).join("\n"))
printzz(zigzag(6))</syntaxhighlight>
{{out}}
<pre>
0 2 3 9 10 20
1 4 8 11 19 21
5 7 12 18 22 29
6 13 17 23 28 30
14 16 24 27 31 34
15 25 26 32 33 35
</pre>
=={{header|360 Assembly}}==
<
ZIGZAGMA CSECT
USING ZIGZAGMA,R12 set base register
Line 112 ⟶ 139:
T DS (N*N)H t(n,n) matrix
YREGS
END ZIGZAGMA</
{{out}}
<pre>
Line 120 ⟶ 147:
9 11 17 20 22
10 18 19 23 24
</pre>
=={{header|Action!}}==
<syntaxhighlight lang="action!">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)
BYTE start,end
INT dir,i,j
start=0 end=size*size-1
i=0 j=0 dir=1
DO
a(Index(size,i,j))=start
a(Index(size,size-1-i,size-1-j))=end
start==+1 end==-1
i==+dir j==-dir
IF i<0 THEN
i==+1 dir=-dir
ELSEIF j<0 THEN
j==+1 dir=-dir
FI
UNTIL start>=end
OD
IF start=end THEN
a(Index(size,i,j))=start
FI
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</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Zig-zag_matrix.png Screenshot from Atari 8-bit computer]
<pre>
Matrix size: 5
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
Matrix size: 6
0 1 5 6 14 15
2 4 7 13 16 25
3 8 12 17 24 26
9 11 18 23 27 32
10 19 22 28 31 33
20 21 29 30 34 35
</pre>
=={{header|ActionScript}}==
<syntaxhighlight lang="as">
package
{
Line 160 ⟶ 270:
}
}
}</syntaxhighlight>
=={{header|Ada}}==
<
procedure Test_Zig_Zag is
Line 213 ⟶ 322:
begin
Put (Zig_Zag (5));
end Test_Zig_Zag;</
The function Zig_Zag generates a square matrix filled as requested by the task.
Line 227 ⟶ 336:
=={{header|Agena}}==
Tested with Agena 2.9.5 Win32
<
makeZigZag := proc( n :: number ) :: table is
Line 274 ⟶ 383:
print()
od
epocs</
{{out}}
<pre>
Line 292 ⟶ 401:
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<syntaxhighlight lang
PROC zig zag = (INT n)[,]INT: (
PROC move = (REF INT i, j)VOID: (
IF j < n THEN
Line 326 ⟶ 436:
[,]INT result = zig zag(dim);
FOR i TO dim DO
print((
FOR j TO dim DO
print(( whole( result[i,j], -3 ), IF j /= dim THEN "," ELSE "" FI ))
OD;
print((IF i = dim THEN "))" ELSE ")," FI, new line))
OD
#FI#
</syntaxhighlight>
{{out}}
<pre>
(( 0, 1, 5, 6, 14),
( 2, 4, 7, 13, 15),
Line 341 ⟶ 452:
( 10, 18, 19, 23, 24))
</pre>
=={{header|ALGOL W}}==
Based on the Agena sample.
<
% z is returned holding a zig-zag matrix of order n, z must be at least n x n %
procedure makeZigZag ( integer value n
Line 409 ⟶ 512:
end
end.</
{{out}}
<pre>
Line 423 ⟶ 526:
{{trans|J}}
<
zzSq ← {zz,⍨⍵} ⍝ Square zigzag
zzSq 5
Line 430 ⟶ 533:
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24</
=={{header|AppleScript}}==
Line 437 ⟶ 540:
Here's a vector & matrix boundary detection approach to the Zig-zap matrix:
<
-- Create an empty matrix.
Line 473 ⟶ 576:
set end of i to return
end repeat
return return & m as string</
But this can be improved upon by building the matrix by populating empty AppleScript lists (it's about 50% faster when n=50):<
set m to {}
Line 507 ⟶ 610:
set i's contents to (i as string) & return
end repeat
return return & m as string</syntaxhighlight>
{{out}} for both scripts is:<pre>
0 1 5 6 14
2 4 7 13 15
Line 515 ⟶ 617:
9 11 17 20 22
10 18 19 23 24
===Recursive===
By functional composition:
<
on zigzagMatrix(n)
Line 677 ⟶ 779:
{}
end if
end tail</
{{Out}}
<pre>{{0, 1, 5, 6, 14},
Line 684 ⟶ 786:
{9, 11, 17, 20, 22},
{10, 18, 19, 23, 24}}</pre>
----
===Optimised iterative===
This is an optimised version of the second iterative script above, with the rendition to text kept separate and corrected. With n = 50, it's about 7.6 times as fast as the script on which it's based.
<syntaxhighlight lang="applescript">on zigzagMatrix(n)
script o
property matrix : {} -- Matrix list.
property row : missing value -- Row sublist.
end script
repeat n times
set end of o's matrix to {} -- Build a foundation for the matrix out of n empty lists.
end repeat
set {r, d} to {1, -1} -- Row index and direction to next insertion row (negative = row above).
repeat with v from 0 to (n ^ 2) - 1 -- Values to insert.
set o's row to o's matrix's item r
repeat while ((count o's row) = n)
set r to r + 1
set d to 1
set o's row to o's matrix's item r
end repeat
set end of o's row to v
set r to r + d
if (r < 1) then
set r to 1
set d to -d
else if (r > n) then
set r to n
set d to -d
else if ((r > 1) and ((count o's matrix's item (r - 1)) = 1)) then
set d to -d
end if
end repeat
return o's matrix
end zigzagMatrix
-- Demo:
on matrixToText(matrix, w)
script o
property matrix : missing value
property row : missing value
end script
set o's matrix to matrix
set padding to " "
repeat with r from 1 to (count o's matrix)
set o's row to o's matrix's item r
repeat with i from 1 to (count o's row)
set o's row's item i to text -w thru end of (padding & o's row's item i)
end repeat
set o's matrix's item r to join(o's row, "")
end repeat
return join(o's matrix, linefeed)
end matrixToText
on join(lst, delim)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to delim
set txt to lst as text
set AppleScript's text item delimiters to astid
return txt
end join
set n to 5
set matrix to zigzagMatrix(n)
linefeed & matrixToText(matrix, (count (n ^ 2 - 1 as integer as text)) + 2) & linefeed</syntaxhighlight>
{{output}}
<pre>
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
</pre>
=={{header|Applesoft BASIC}}==
<
110 S2 = S ^ 2 : REM SQUARED
120 H = S2 / 2 : REM HALFWAY
Line 710 ⟶ 890:
340 NEXT X
350 PRINT
360 NEXT Y</
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">zigzag: function [n][
result: map 1..n 'x -> map 1..n => 0
x: 1, y: 1, v: 0, d: 1
while [v < n^2][
if? all? @[1 =< x x =< n 1 =< y y =< n][
set get result (y-1) (x-1) v
x: x + d, y: y - d, v: v + 1
]
else[if? x > n [x: n, y: y + 2, d: neg d]
else[if? y > n [x: x + 2, y: n, d: neg d]
else[if? x < 1 [x: 1, d: neg d]
else[if y < 1 [y: 1, d: neg d]
]
]
]
]
]
result
]
zz: zigzag 5
loop zz 'row -> print map row 'col [pad to :string col 3]</syntaxhighlight>
{{out}}
<pre> 0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24</pre>
=={{header|ATS}}==
<syntaxhighlight lang="ats">
(* ****** ****** *)
//
Line 776 ⟶ 991:
(* ****** ****** *)
</syntaxhighlight>
=={{header|AutoHotkey}}==
{{trans|lisp}}
contributed by Laszlo on the ahk [http://www.autohotkey.com/forum/post-276307.html#276307 forum].
<
v := x := y := 1 ; initial values
Loop % n*n { ; for every array element
Line 801 ⟶ 1,016:
t .= "`n" ; row is complete
}
MsgBox %t% ; show output</
=={{header|AutoIt}}==
<
#include <Array.au3>
$Array = ZigZag(5)
Line 831 ⟶ 1,046:
Next
Return $av_array
EndFunc ;==>ZigZag</syntaxhighlight>
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f ZIG-ZAG_MATRIX.AWK [-v offset={0|1}] [size]
BEGIN {
Line 863 ⟶ 1,077:
}
exit(0)
}</syntaxhighlight>
{{out}}
<pre>
Line 875 ⟶ 1,088:
=={{header|BBC BASIC}}==
<
DIM array%(Size%-1,Size%-1)
Line 897 ⟶ 1,110:
NEXT
PRINT
NEXT row%</
{{out}}
<pre>
Line 906 ⟶ 1,119:
10 18 19 23 24
</pre>
=={{header|Beads}}==
This is a translation of the [[Zig-zag_matrix#C++|C++]] example.
<syntaxhighlight lang="beads">beads 1 program 'Zig-zag Matrix'
calc main_init
var test : array^2 of num = create_array(5)
printMatrix(test)
calc create_array(
dimension:num
):array^2 of num
var
result : array^2 of num
lastValue = dimension^2 - 1
loopFrom
loopTo
row
col
currDiag = 0
currNum = 0
loop
if (currDiag < dimension) // if doing the upper-left triangular half
loopFrom = 1
loopTo = currDiag + 1
else // doing the bottom-right triangular half
loopFrom = currDiag - dimension + 2
loopTo = dimension
loop count:c from:loopFrom to:loopTo
var i = loopFrom + c - 1
if (rem(currDiag, 2) == 0) // want to fill upwards
row = loopTo - i + loopFrom
col = i
else // want to fill downwards
row = i
col = loopTo - i + loopFrom
result[row][col] = currNum
inc currNum
inc currDiag
if (currNum > lastValue)
exit
return result
calc printMatrix(
matrix:array^2 of num
)
var dimension = tree_count(matrix)
var maxDigits = 1 + lg((dimension^2-1), base:10)
loop across:matrix ptr:rowp index:row
var tempstr : str
loop across:rowp index:col
tempstr = tempstr & " " & to_str(matrix[row][col], min:maxDigits)
log(tempstr)</syntaxhighlight>
{{out}}
<pre> 0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24</pre>
=={{header|Befunge}}==
The size, ''N'', is specified by the first value on the stack - 5 in the example below. The upper limit is constrained only by the range of the playfield cells used for variables, since we're using an algorithm that calculates the values on the fly rather than building them up in memory. On an 8 bit interpreter this means an upper limit of at least 127, but with an extended cell range the size of ''N'' can be almost unlimited.
<
v:++!\**2p01:+1g01:g02$$_>>#^4#00#+p#1:#+1#g0#0g#3<^/+ 55\_$:>55+/\|
>55+,20g!00g10g`>#^_$$$@^!`g03g00!g04++**2p03:+1g03!\*+1*2g01:g04.$<</
{{out}}
Line 920 ⟶ 1,192:
9 11 17 20 22
10 18 19 23 24</pre>
=={{header|BQN}}==
<syntaxhighlight lang="bqn">Flip ← {m←2|+⌜˜↕≠𝕩 ⋄ (⍉𝕩׬m)+𝕩×m}
Zz ← {Flip ⍋∘⍋⌾⥊+⌜˜↕𝕩}</syntaxhighlight>
Example:
<syntaxhighlight lang="bqn">Zz 5</syntaxhighlight>
<pre>
┌─
╵ 0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
┘
</pre>
([https://mlochbaum.github.io/BQN/try.html#code=RmxpcCDihpAge23ihpAyfCvijJzLnOKGleKJoPCdlakg4ouEICjijYnwnZWpw5fCrG0pK/CdlanDl219ClpaICAg4oaQIHtGbGlwIOKNi+KImOKNi+KMvuKliivijJzLnOKGlfCdlal9CgpaWiA1 online REPL])
=={{header|C}}==
<
#include <stdlib.h>
Line 944 ⟶ 1,236:
/* free(s) */
return 0;
}</
{{out}}
<pre>% ./a.out 7
Line 957 ⟶ 1,249:
=={{header|C sharp}}==
<
{
int[,] result = new int[n, n];
Line 981 ⟶ 1,273:
result[i, j] = start;
return result;
}</
=={{header|C++}}==
<
#include <memory> // for auto_ptr
#include <cmath> // for the log10 and floor functions
Line 1,064 ⟶ 1,356:
{
printZigZagArray( getZigZagArray( 5 ) );
}</
{{out}}
<pre>
Line 1,075 ⟶ 1,367:
=={{header|Ceylon}}==
<
value data = Array {
Line 1,124 ⟶ 1,416:
value zz = ZigZag(5);
zz.display();
}</
=={{header|Clojure}}==
Purely functional approach.
<
(lazy-seq
(when-let [n (first sizes)]
Line 1,160 ⟶ 1,452:
( 9 11 18 23 27 32)
(10 19 22 28 31 33)
(20 21 29 30 34 35))</
=={{header|CoffeeScript}}==
<
# Calculate a zig-zag pattern of numbers like so:
# 0 1 5
Line 1,204 ⟶ 1,496:
console.log "---- n=#{n}"
console.log zig_zag_matrix(n)
console.log "\n"</syntaxhighlight>
{{out}}
Line 1,236 ⟶ 1,527:
=={{header|Common Lisp}}==
==={{trans|Java}} (but with zero-based indexes and combining the even and odd cases)===
<
(flet ((move (i j)
(if (< j (1- n))
Line 1,249 ⟶ 1,540:
(setf (values x y) (move x y))
(setf (values y x) (move y x)))
finally (return a))))</
===An alternative approach===
<
; ZigZag
;
Line 1,270 ⟶ 1,561:
(format t "~3d" (nth j st))
(setf (nth j st) (+ (nth j st) (nth j dx)))))))
</syntaxhighlight>
(ZigZag 5) Produces:
<pre>
Line 1,305 ⟶ 1,596:
=={{header|Crystal}}==
{{trans|Ruby}}
<
(seq=(0...n).to_a).product(seq)
.sort_by {|x,y| [x+y, (x+y).even? ? y : -y]}
Line 1,316 ⟶ 1,607:
end
print_matrix zigzag(5)</
{{out}}
<pre>
Line 1,328 ⟶ 1,619:
=={{header|D}}==
{{trans|Common Lisp}}
<
static void move(in int n, ref int i, ref int j)
pure nothrow @safe @nogc {
Line 1,351 ⟶ 1,642:
writefln("%(%(%2d %)\n%)", 5.zigZag);
}</
{{out}}
<pre> 0 1 5 6 14
Line 1,362 ⟶ 1,653:
{{trans|Scala}}
Same output.
<
int[][] zigZag(in int n) pure nothrow {
Line 1,379 ⟶ 1,670:
void main() {
writefln("%(%(%2d %)\n%)", 5.zigZag);
}</
=={{header|E}}==
Line 1,387 ⟶ 1,678:
Then the code. {{trans|D}}
<
def move(&i, &j) {
if (j < (n - 1)) {
Line 1,410 ⟶ 1,701:
}
return array
}</
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
<syntaxhighlight lang="Delphi">
type TMatrix = array of array of double;
procedure DisplayMatrix(Memo: TMemo; Mat: TMatrix);
{Display specified matrix}
var X,Y: integer;
var S: string;
begin
S:='';
for Y:=0 to High(Mat[0]) do
begin
S:=S+'[';
for X:=0 to High(Mat) do
S:=S+Format('%4.0f',[Mat[X,Y]]);
S:=S+']'+#$0D#$0A;
end;
Memo.Lines.Add(S);
end;
procedure ZigzagMatrix(Memo: TMemo);
var Mat: TMatrix;
var X,Y,Inx,Dir: integer;
const Size = 10;
procedure Toggle(var I: integer);
{Toggle Direction and increment I}
begin
Dir:=-Dir;
Inc(I);
end;
procedure Step(var X,Y: integer);
{Take one step "Dir" direction}
begin
X:=X+Dir;
Y:=Y-Dir;
end;
begin
SetLength(Mat,Size,Size);
Inx:=0; X:=0; Y:=0; Dir:=1;
repeat
begin
Mat[X,Y]:=Inx;
if (X+Dir)>=Size then Toggle(Y)
else if (Y-Dir)>=Size then Toggle(X)
else if (X+Dir)<0 then Toggle(Y)
else if (Y-Dir)<0 then Toggle(X)
else Step(X,Y);
Inc(Inx);
end
until Inx>=Size*Size;
DisplayMatrix(Memo,Mat);
end;
</syntaxhighlight>
{{out}}
<pre>
[ 0 1 5 6 14 15 27 28 44 45]
[ 2 4 7 13 16 26 29 43 46 63]
[ 3 8 12 17 25 30 42 47 62 64]
[ 9 11 18 24 31 41 48 61 65 78]
[ 10 19 23 32 40 49 60 66 77 79]
[ 20 22 33 39 50 59 67 76 80 89]
[ 21 34 38 51 58 68 75 81 88 90]
[ 35 37 52 57 69 74 82 87 91 96]
[ 36 53 56 70 73 83 86 92 95 97]
[ 54 55 71 72 84 85 93 94 98 99]
Elapsed Time: 1.576 ms.
</pre>
=={{header|Elena}}==
{{trans|C#}}
ELENA 5.0:
<
extension op : IntNumber
Line 1,458 ⟶ 1,833:
{
console.printLine(5.zigzagMatrix()).readChar()
}</
=={{header|Elixir}}==
<
require Integer
def zigzag(n) do
Line 1,475 ⟶ 1,850:
end
RC.zigzag(5)</
{{out}}
Line 1,484 ⟶ 1,859:
9 11 17 20 22
10 18 19 23 24
</pre>
=={{header|EMal}}==
<syntaxhighlight lang="emal">
fun zigzag = List by int n
List matrix = List[].with(n)
for int y = 0; y < n; y++ do matrix[y] = int[].with(n) end
int y, x = 1
for int value = 0; value < n * n; value++
matrix[y - 1][x - 1] = value
if (y + x) % 2 == 0
if x < n do x++
else do y += 2 end
if y > 1 do y-- end
else
if y < n do y++
else do x += 2 end
if x > 1 do x-- end
end
end
return matrix
end
fun dump = void by List matrix
int max = length(text!(matrix.length ** 2)) + 1
for each List row in matrix
for each int value in row
write(" " * (max - length(text!value)) + value)
end
writeLine()
end
end
dump(zigzag(5))
writeLine()
dump(zigzag(10))
</syntaxhighlight>
{{out}}
<pre>
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
0 1 5 6 14 15 27 28 44 45
2 4 7 13 16 26 29 43 46 63
3 8 12 17 25 30 42 47 62 64
9 11 18 24 31 41 48 61 65 78
10 19 23 32 40 49 60 66 77 79
20 22 33 39 50 59 67 76 80 89
21 34 38 51 58 68 75 81 88 90
35 37 52 57 69 74 82 87 91 96
36 53 56 70 73 83 86 92 95 97
54 55 71 72 84 85 93 94 98 99
</pre>
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module( zigzag ).
Line 1,515 ⟶ 1,943:
next_indexes( {0, Y}, _Max ) when Y rem 2 =:= 1 -> {0, Y + 1};
next_indexes( {X, Y}, _Max ) when (X + Y) rem 2 =:= 0 -> {X + 1, Y - 1};
next_indexes( {X, Y}, _Max ) when (X + Y) rem 2 =:= 1 -> {X - 1, Y + 1}.</syntaxhighlight>
{{out}}
<pre>
Line 1,528 ⟶ 1,955:
=={{header|ERRE}}==
<
!$DYNAMIC
Line 1,556 ⟶ 1,983:
PRINT
END FOR
END PROGRAM</
{{out}}
<pre> 0 1 5 6 14
Line 1,566 ⟶ 1,993:
=={{header|Euphoria}}==
{{trans|C#}}
<
sequence s
integer i, j, d, max
Line 1,585 ⟶ 2,012:
end function
? zigzag(5)</
{{out}}
{
Line 1,596 ⟶ 2,023:
=={{header|F_Sharp|F#}}==
<
//Produce a zig zag matrix - Nigel Galloway: April 7th., 2015
let zz l a =
Line 1,611 ⟶ 2,038:
| _ -> gng (n-1, i+1, g+1, 2)
gng (0, 0, 0, 2)
</syntaxhighlight>
{{out}}
<syntaxhighlight lang
<pre>
[[0; 1; 5; 6; 14]
Line 1,621 ⟶ 2,048:
[10; 18; 19; 23; 24]]
</pre>
<syntaxhighlight lang
<pre>
[[0; 1; 5; 6; 14; 15; 27; 28]
Line 1,633 ⟶ 2,060:
</pre>
Let's try something a little less square man
<syntaxhighlight lang
<pre>
[[0; 1; 5; 6; 14; 15; 24; 25]
Line 1,645 ⟶ 2,072:
This version follows the algorithm laid out in the comments of the first JavaScript (ES5) functional example, though it is not exactly a straight translation.
{{works with|Factor|0.99 2019-03-17}}
<
sequences sequences.cords sequences.extras ;
IN: rosetta-code.zig-zag-matrix
Line 1,669 ⟶ 2,096:
: zig-zag-demo ( -- ) 5 zig-zag-matrix simple-table. ;
MAIN: zig-zag-demo</
{{out}}
<pre>
Line 1,680 ⟶ 2,107:
The following example is an implementation of a J routine with an [http://rosettacode.org/wiki/Talk:Zig-zag_matrix#reading_the_J_examples excellent walkthrough on the talk page]. Luckily, we can mimic the "classification" step with the composition of 3 existing Factor words: <code>zip-index expand-keys-push-at values</code> and the <code>inverse-permutation</code> word is the same concept as J's grade, so this is fairly succinct.
{{works with|Factor|0.99 2020-01-23}}
<
math.combinatorics math.matrices prettyprint sequences ;
Line 1,690 ⟶ 2,117:
] [ group ] bi ;
5 <zig-zag-matrix> simple-table.</
{{out}}
<pre>
Line 1,701 ⟶ 2,128:
=={{header|Fan}}==
<
**
Line 1,791 ⟶ 2,218:
print(zag(8))
}
}</
=={{header|Forth}}==
<
: south diag abs + cell+ ;
Line 1,843 ⟶ 2,270:
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24 ok</
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
IMPLICIT NONE
Line 1,884 ⟶ 2,311:
END DO
END PROGRAM ZIGZAG</
=={{header|FreeBASIC}}==
<
Dim As Integer n
Line 1,960 ⟶ 2,387:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,977 ⟶ 2,404:
=={{header|GAP}}==
<
local a, i, j, k;
a := NullMat(n, n);
Line 2,012 ⟶ 2,439:
# [ 3, 8, 12, 16, 21 ],
# [ 9, 11, 17, 20, 22 ],
# [ 10, 18, 19, 23, 24 ] ]</
=={{header|Go}}==
{{trans|Groovy}} Edge direct algorithm
<
import (
Line 2,062 ⟶ 2,489:
}
}
}</
{{out}}
<pre>
Line 2,078 ⟶ 2,505:
and calculates the transform onto the grid.
<
grid = new int[n][n]
i = 0
Line 2,088 ⟶ 2,515:
}
grid
}</
{{out}}
Line 2,104 ⟶ 2,531:
Ported from the Java example
<
move = { i, j -> j < n - 1 ? [i <= 0 ? 0 : i-1, j+1] : [i+1, j] }
grid = new int[n][n]
Line 2,114 ⟶ 2,541:
}
grid
}</
{{out}}
Line 2,129 ⟶ 2,556:
Ported from the Python example with some input from J
<
(0..<n*n).collect { [x:it%n,y:(int)(it/n)] }.sort { c->
[c.x+c.y, (((c.x+c.y)%2) ? c.y : -c.y)]
}.with { l -> l.inject(new int[n][n]) { a, c -> a[c.y][c.x] = l.indexOf(c); a } }
}</
{{out}}
Line 2,149 ⟶ 2,576:
Computing the array:
<
import Text.Printf (printf)
import Data.List (sortBy)
Line 2,163 ⟶ 2,590:
zigZag upper = array b $ zip (sortBy compZig (range b)) [0 ..]
where
b = ((0, 0), upper)</
<tt>compZig</tt> compares coordinates using the order of a zigzag walk:
Line 2,174 ⟶ 2,601:
Displaying the array (not part of the task):
<
show2d a =
unlines
Line 2,185 ⟶ 2,612:
axis f = [f l .. f h]
main = mapM_ (putStr . ('\n' :) . show2d . zigZag) [(3, 3), (4, 4), (10, 2)]</
Or, building a list of lists with mapAccumL:
<
import Data.List (mapAccumL)
import Data.Bool (bool)
Line 2,214 ⟶ 2,641:
putStrLn $
unlines $
concatMap unpack . fmap (justifyRight 3 ' ' . pack . show) <$> zigZag 5</
{{Out}}
<pre> 0 1 5 6 14
Line 2,225 ⟶ 2,652:
This solution works for both Icon and Unicon.
<
n := integer(!args) | 5
every !(A := list(n)) := list(n)
Line 2,249 ⟶ 2,676:
then if x[2] = n then [x[1]+1, x[2]] else [max(1, x[1]-1), x[2]+1]
else if x[1] = n then [x[1], x[2]+1] else [x[1]+1, max(1, x[2]-1)]
end</
{{out}}
Line 2,262 ⟶ 2,689:
=={{header|IS-BASIC}}==
<
110 LET SIZE=5
120 NUMERIC A(1 TO SIZE,1 TO SIZE)
Line 2,289 ⟶ 2,716:
350 NEXT
360 PRINT
370 NEXT</
=={{header|J}}==
A succinct way:
<
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24</
This version is longer, but more "mathematical" and less "procedural":
<
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24</
Leveraging a [[Talk:Zig Zag#reading_the_J_examples|useful relationship among the indices]]:
<
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24</
(Also, of course, <code>($ [: /:@; <@|.`</.@i.)@,~0</code> creates a result with 0 rows and 0 columns. And, with an argument of 1, the result has one row and one column with the value <code>0</code>. And, the other expressions behave the same.)
Furthermore, by simply ''removing'' the trailing <tt>@,~</tt>
from the solutions, they automatically generalize
to rectangular (non-square) matrices:
<
0 1 5
2 4 6
3 7 11
8 10 12
9 13 14</
=={{header|Java}}==
{{trans|Ada}}
<
{
int[][] data = new int[size][size];
Line 2,361 ⟶ 2,788:
}
return data;
}</
=={{header|JavaScript}}==
Line 2,372 ⟶ 2,799:
Subclasses the Matrix class defined at [[Matrix Transpose#JavaScript]]
<
this.height = n;
this.width = n;
Line 2,403 ⟶ 2,830:
z = new ZigZagMatrix(4);
print(z);</
{{out}}
<pre>0,1,5,6,14
Line 2,420 ⟶ 2,847:
====ES5====
<
// Read range of values into a series of 'diagonal rows'
Line 2,516 ⟶ 2,943:
}));
})(5);</
{{Out}}
<
[2, 4, 7, 13, 15],
[3, 8, 12, 16, 21],
[9, 11, 17, 20, 22],
[10, 18, 19, 23, 24]]</
====ES6====
<
// diagonals :: n -> [[n]]
Line 2,587 ⟶ 3,014:
);
})(5);</
{{Out}}
<
[2, 4, 7, 13, 15],
[3, 8, 12, 16, 21],
[9, 11, 17, 20, 22],
[10, 18, 19, 23, 24]]</
=={{header|Joy}}==
<syntaxhighlight lang="joy">
(*
From the library.
Line 2,648 ⟶ 3,075:
concat [step '\n putch] cons step.
11 zigzag.</
=={{header|jq}}==
Infrastructure:
<
def matrix(m; n; init):
if m == 0 then []
Line 2,670 ⟶ 3,097:
(""; . + reduce range(0;$length) as $j
(""; "\(.) \($in[$i][$j] | right )" ) + "\n" ) ;
</syntaxhighlight>
Create a zigzag matrix by zigzagging:
<
# unless m == n*n, place m at (i,j), pointing
Line 2,690 ⟶ 3,117:
# Example
zigzag(5) | neatly(4)</
{{out}}
<pre>
Line 2,701 ⟶ 3,128:
</pre>
=== another solution ===
<
#
# solve zigzag matrix by constructing list of 2n+1 column "runs"
Line 2,765 ⟶ 3,192:
| shiftdown # shift right runs down
| shiftleft # shift rows left
| format # format final result</syntaxhighlight>
{{out}}
<pre>
Line 2,783 ⟶ 3,208:
=={{header|Julia}}==
=== simple solution ===
<
matrix = zeros(Int, n, n)
x, y = 1, 1
Line 2,807 ⟶ 3,232:
end
return matrix
end</
{{out}}
Line 2,823 ⟶ 3,248:
'''Zig-Zag Iterator'''
<syntaxhighlight lang="julia">
immutable ZigZag
m::Int
Line 2,883 ⟶ 3,308:
return (s, zzs)
end
</syntaxhighlight>
'''Helper Functions'''
<syntaxhighlight lang="julia">
using Formatting
Line 2,911 ⟶ 3,336:
return s
end
</syntaxhighlight>
'''Main'''
<syntaxhighlight lang="julia">
n = 5
println("The n = ", n, " zig-zag matrix:")
Line 2,941 ⟶ 3,366:
end
println(pretty(a))
</syntaxhighlight>
{{out}}
Line 2,968 ⟶ 3,393:
=={{header|Klingphix}}==
<
Line 2,998 ⟶ 3,423:
nl "End " input</
{{out}}
<pre>0 1 5 6 14
Line 3,007 ⟶ 3,432:
End</pre>
=={{header|K}}==
'''Works with:''' [[ngnk|ngn/k]]
<syntaxhighlight>
f:{grid:+x#<<a,'(!#a)*- 2!a:+/!x,:x
padded:(-#$-1+*/x)$$grid
`0:" "/'padded}
f 5
</syntaxhighlight>
{{out}}
<pre>
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
</pre>
=={{header|Kotlin}}==
<
typealias Vector = IntArray
Line 3,045 ⟶ 3,490:
printMatrix(zigzagMatrix(5))
printMatrix(zigzagMatrix(10))
}</
{{out}}
Line 3,066 ⟶ 3,511:
54 55 71 72 84 85 93 94 98 99
</pre>
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">
#!/bin/ksh
# Produce a zig-zag array.
# # Variables:
#
integer DEF_SIZE=5 # Default size = 5
arr_size=${1:-$DEF_SIZE} # $1 = size, or default
# # Externals:
#
# # Functions:
#
######
# main #
######
integer i j n
typeset -a zzarr
for (( i=n=0; i<arr_size*2; i++ )); do
for (( j= (i<arr_size) ? 0 : i-arr_size+1; j<=i && j<arr_size; j++ )); do
(( zzarr[(i&1) ? j*(arr_size-1)+i : (i-j)*arr_size+j] = n++ ))
done
done
for ((i=0; i<arr_size*arr_size; i++)); do
printf "%3d " ${zzarr[i]}
(( (i+1)%arr_size == 0 )) && printf "\n"
done</syntaxhighlight>
{{out}}<pre>
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
0 1 5 6 14 15 27 28 44
2 4 7 13 16 26 29 43 45
3 8 12 17 25 30 42 46 59
9 11 18 24 31 41 47 58 60
10 19 23 32 40 48 57 61 70
20 22 33 39 49 56 62 69 71
21 34 38 50 55 63 68 72 77
35 37 51 54 64 67 73 76 78
36 52 53 65 66 74 75 79 80</pre>
=={{header|Lasso}}==
<
var(
'square' = array
Line 3,145 ⟶ 3,641:
$square;
</syntaxhighlight>
=={{header|Lua}}==
<syntaxhighlight lang="lua">
local zigzag = {}
Line 3,225 ⟶ 3,721:
print(zigzag.new(5))
</syntaxhighlight>
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module Lib1 {
Module Global PrintArray(&Ar()) {
if dimension(Ar())<>2 then Error "This is for 2D arrays"
integer i, j, n=dimension(Ar(),1), n1=dimension(Ar(),2)
for i=1 to n
for j=1 to n1
print Ar(i, j),
next
print
next
}
Function Global MakeArray(n as integer=5) {
dim a(1 to n, 1 to n) as integer=0
integer i=1, j=1, z, t1=1
boolean ch=true
for z=0 to n*n-1
if ch then a(i,j)=z else a(j,i)=z
j++
if j>t1 then t1++: j=1:i=t1: ch~ else i--
if i<1 then i=t1 else.if i>n then i=n: j++
if j>n then j=i+2: i=n:ch~
next
=a() // return array (as a pointer)
}
}
Module Zig_Zag_Matrix (n as integer=5) {
Pen 15 {Report "matrix "+n+"x"+n}
integer old_column=tab
Print $(,4) // set column to 4 chars
if random(1,2)=2 then
dim ret()
ret()=makeArray(n) // this get a copy
else
object a=makeArray(n) // but this get the copy of pointer
link a to ret() // ret() is reference to a, to array
end if
PrintArray &ret()
Print $(,old_column)
}
Inline Code Lib1 // just execute the code from module lib1 like was here
Form 60, 36 \\ console 60x36 characters
Report 2, "Zig-zag matrix" // 2 for center
Pen 14 {Zig_Zag_Matrix 1}
Pen 11 {Zig_Zag_Matrix 2}
Pen 14 {Zig_Zag_Matrix 3}
Pen 11 {Zig_Zag_Matrix 4}
Pen 14 {Zig_Zag_Matrix 5}
Pen 11 {Zig_Zag_Matrix 10}
</syntaxhighlight>
=={{header|M4}}==
<
define(`set2d',`define(`$1[$2][$3]',`$4')')
Line 3,257 ⟶ 3,806:
zigzag(`a',5)
show2d(`a',5,5)</
{{out}}
Line 3,271 ⟶ 3,820:
{{trans|Stata}}
Here values are starting at 1. Replace <code><v+~1,v+~2></code> with <code><v,v+~1></code> to start at 0.
<syntaxhighlight lang="maple">zigzag1:=proc(n)
uses ArrayTools;
local i
u:=Replicate(<-1,1>,n):
v:=
v:=Reshape(<v+~1,v+~2>,2*n):
a:=Matrix(n,n):
Line 3,289 ⟶ 3,839:
local i,v,a;
a:=zigzag1(n);
v:=Vector(1..n-1,i->i
for i from 2 to n do
a[n+2-i..n,i]-=v[1..i-1]
od;
a
end:</
<syntaxhighlight lang
{{out}}
<pre>Matrix(6, 6, [[ 1, 2, 6, 7, 15, 16],
<syntaxhighlight lang
{{out}}
<pre>Matrix(6, 6, [[ 1, 2, 6, 7, 15, 16],
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Line 3,322 ⟶ 3,872:
using a direct formula.
The lower-right half is then 'mirrored' from the upper-left half.
<
empty=ReplacePart[empty,{i_,j_}:>1/2 (i+j)^2-(i+j)/2-i (1-Mod[i+j,2])-j Mod[i+j,2]];
ReplacePart[empty,{i_,j_}/;i+j>size+1:> size^2-tmp[[size-i+1,size-j+1]]-1]
]</
Ported from the java-example:
<
data = ConstantArray[0, {size, size}];
i = j = 1;
Line 3,341 ⟶ 3,891:
];
data
]</
Examples:
<
ZigZag2[6] // MatrixForm</
gives back:
Line 3,378 ⟶ 3,928:
But! It is pretty fast for n < 10000.
<
%This is very unintiutive. This algorithm parameterizes the
Line 3,443 ⟶ 3,993:
end</
{{out}}
Line 3,457 ⟶ 4,007:
=={{header|Maxima}}==
<
a: zeromatrix(n, n),
i: 1,
Line 3,478 ⟶ 4,028:
[ 3, 8, 12, 16, 21],
[ 9, 11, 17, 20, 22],
[10, 18, 19, 23, 24]) */</
=={{header|MiniZinc}}==
<syntaxhighlight lang="minizinc">
%Zigzag Matrix. Nigel Galloway, February 3rd., 2020
int: Size;
Line 3,491 ⟶ 4,041:
constraint forall(n in {2*g+((Size) mod 2) | g in 1..(Size-1) div 2})(zigzag[Size,n]=zigzag[Size,n-1]+1 /\ forall(g in 1..Size-n)(zigzag[Size-g,n+g]=zigzag[Size-g+1,n+g-1]+1));
output [show2d(zigzag)];
</syntaxhighlight>
{out}
<pre>
Line 3,513 ⟶ 4,063:
=={{header|Modula-3}}==
<
IMPORT IO, Fmt;
Line 3,560 ⟶ 4,110:
BEGIN
Print(Create(5));
END ZigZag.</
{{out}}
<pre>
Line 3,572 ⟶ 4,122:
=={{header|NetRexx}}==
{{trans|REXX}}
<
options replace format comments java crossref savelog symbols binary
Line 3,613 ⟶ 4,163:
return
</syntaxhighlight>
=={{header|Nim}}==
{{trans|Python}}
<
from strutils import align
from sequtils import newSeqWith
Line 3,647 ⟶ 4,197:
result.add "\n"
echo zigzagMatrix(6)</
{{out}}
<pre> 0 1 5 6 14 15
Line 3,658 ⟶ 4,208:
===Direct coord to number===
This calculates the number for each coordinate directly. This allows to create very large zig-zag matrices. Generates the same output as above.
<
func sumTo(n: Natural): Natural = n * (n+1) div 2
Line 3,680 ⟶ 4,230:
stdout.write(coord2num(row, col, N).`$`.align(width))
stdout.write("\n")
</syntaxhighlight>
=={{header|Objeck}}==
{{trans|Java}}
<
function : native : ZigZag(size : Int) ~ Int[,] {
data := Int->New[size, size];
Line 3,724 ⟶ 4,274:
return data;
}
</syntaxhighlight>
=={{header|OCaml}}==
Line 3,730 ⟶ 4,280:
{{trans|Common Lisp}}
<
(* move takes references and modifies them directly *)
let move i j =
Line 3,748 ⟶ 4,298:
move y x
done;
a</
=={{header|Octave}}==
{{trans|Stata}}
<
j = 1:n;
u = repmat([-1; 1], n, 1);
Line 3,780 ⟶ 4,330:
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24</
Alternate solution, filling pairs of diagonals.
<
a = zeros(n, n);
for k=1:n
Line 3,801 ⟶ 4,351:
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24</
==Inspired by Rascal==
<
#{
Produce a zigzag matrix. Nigel Galloway, January 26th., 2020.
Line 3,862 ⟶ 4,412:
11 19 20 24 25
#}
</syntaxhighlight>
=={{header|ooRexx}}==
{{trans|Java}}
<syntaxhighlight lang="oorexx">
call printArray zigzag(3)
say
Line 3,909 ⟶ 4,459:
say line
end
</syntaxhighlight>
{{out}}
<pre>
Line 3,930 ⟶ 4,480:
=={{header|Oz}}==
Implemented as a state machine:
<
%% state move success failure
States = unit(right: [ 1# 0 downLeft downInstead]
Line 3,968 ⟶ 4,518:
end
in
{Inspect {CreateZigZag 5}}</
=={{header|PARI/GP}}==
{{trans|C.23}}
<
my(M=matrix(n,n),i,j,d=-1,start,end=n^2-1);
while(ct--,
Line 3,992 ⟶ 4,542:
if(start>end,return(M))
)
};</
=={{header|Pascal}}==
<
const
Line 4,061 ⟶ 4,611:
writeln;
end;
end.</
{{out}}
Line 4,086 ⟶ 4,636:
{{trans|Seed7}} <br>
<syntaxhighlight lang="pascal">
Program zigzag;
{$APPTYPE CONSOLE}
Line 4,127 ⟶ 4,677:
end.
</syntaxhighlight>
{{out}} Size 5
Line 4,151 ⟶ 4,701:
=={{header|Perl}}==
<
sub zig_zag {
Line 4,175 ⟶ 4,725:
my @zig_zag_matrix = zig_zag(5);
say join "\t", @{$_} foreach @zig_zag_matrix;
</syntaxhighlight>
{{trans|Haskell}}
<
my ($w, $h, @r, $n) = @_;
Line 4,194 ⟶ 4,744:
}
print map{ "@$_\n" } zig_zag(3, 5);</
=={{header|Phix}}==
{{Trans|C#}}
<!--<syntaxhighlight lang="phix">(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;">9</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">zstart</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">zend</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: #000000;">1</span>
<span style="color: #000080;font-style:italic;">--integer zstart = 1, zend = n*n</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;">zend</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: #004080;">integer</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;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</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;">zstart</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">zstart</span><span style="color: #0000FF;">=</span><span style="color: #000000;">zend</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">zstart</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">m</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</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;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</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;">zend</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">zend</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">x</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">d</span>
<span style="color: #000000;">y</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">d</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">x</span><span style="color: #0000FF;"><</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">x</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">d</span>
<span style="color: #008080;">elsif</span> <span style="color: #000000;">y</span><span style="color: #0000FF;"><</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">y</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">d</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</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;">n</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">m</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">))</span>
<!--</syntaxhighlight>-->
Alternative:
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">5</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: #000000;">1</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: #004080;">integer</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;">1</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</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: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">m</span><span style="color: #0000FF;">[</span><span style="color: #000000;">y</span><span style="color: #0000FF;">][</span><span style="color: #000000;">x</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;">d</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">mod</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: #000000;">2</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</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: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">y</span><span style="color: #0000FF;"><</span><span style="color: #000000;">n</span><span style="color: #0000FF;">?{</span><span style="color: #000000;">x</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;">1</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: #008080;">else</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: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;"><</span><span style="color: #000000;">n</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;">y</span><span style="color: #0000FF;">></span><span style="color: #000000;">1</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: #000000;">1</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</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;">n</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">m</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">))</span>
<!--</syntaxhighlight>-->
=={{header|Phixmonti}}==
<
0 Size repeat Size repeat
Line 4,268 ⟶ 4,823:
ENDFOR
nl
ENDFOR</
=={{header|PHP}}==
<
$matrix = array();
for ($i = 0; $i < $num; $i++){
Line 4,302 ⟶ 4,857:
}
return $matrix;
}</
=={{header|PicoLisp}}==
Line 4,308 ⟶ 4,863:
a two-dimensional structure and is normally used
for simulations and board games.
<
(de zigzag (N)
Line 4,327 ⟶ 4,882:
(for This L (prin (align 3 (: val))))
(prinl) )
(zigzag 5) )</
{{out}}
<pre> 1 2 6 7 15
Line 4,336 ⟶ 4,891:
=={{header|PL/I}}==
<
/* in a zig-zag fashion. */
/* N is the length of one side of the square. */
Line 4,386 ⟶ 4,941:
put skip edit (a(i,*)) (f(4));
end;
end;</
{{out}}
<pre> 0 1 5 6 14
Line 4,396 ⟶ 4,951:
=={{header|PlainTeX}}==
The code works with any etex engine.
<
\def\fornum#1=#2to#3(#4){%
\edef#1{\number\numexpr#2}\edef\fornumtemp{\noexpand\fornumi\expandafter\noexpand\csname fornum\string#1\endcsname
Line 4,417 ⟶ 4,972:
}
\zzmat{5}
\bye</
pdf output:
Line 4,432 ⟶ 4,987:
and also draws lines to show the path.
<
%%BoundingBox: 0 0 300 200
/size 9 def % defines row * column (9*9 -> 81 numbers,
Line 4,486 ⟶ 5,041:
stroke showpage
} if
%%EOF</
=={{header|PowerShell}}==
<
$zigzag=New-Object 'Object[,]' $n,$n
$nodd = $n -band 1
Line 4,527 ⟶ 5,082:
} )"
}
}</
===An Alternate Display===
Display the zig-zag matrix using the <code>Format-Wide</code> cmdlet:
<syntaxhighlight lang="powershell">
zigzag 5 | Format-Wide {"{0,2}" -f $_} -Column 5 -Force
</syntaxhighlight>
{{Out}}
<pre>
Line 4,544 ⟶ 5,099:
=={{header|Prolog}}==
{{Works with|
<
zig_zag(N, N).
Line 4,622 ⟶ 5,177:
print_val(V) :-
writef('%3r ', [V]).
</syntaxhighlight>
{{out}}
<pre>?- zig_zag(5).
Line 4,653 ⟶ 5,208:
=={{header|PureBasic}}==
{{trans|AutoHotkey}} <br>
<
Protected i, v, x, y
Line 4,705 ⟶ 5,260:
Input()
CloseConsole()
EndIf</
{{out}}
<pre>Zig-zag matrix of size 5
Line 4,730 ⟶ 5,285:
by [http://paddy3118.blogspot.com/2008/08/zig-zag.html paddy3118].
{{Works with|Python|3}}
<
'''zigzag rows'''
def compare(xy):
Line 4,751 ⟶ 5,306:
printzz(zigzag(6))</
{{out}}
<pre> 0 2 3 9 10 20
Line 4,761 ⟶ 5,316:
===Alternative version, {{trans|Common Lisp}}===
<
# pylint: disable=invalid-name
# pylint: disable=unused-argument
Line 4,795 ⟶ 5,350:
from pprint import pprint
pprint(mat)
</syntaxhighlight>
{{out}}
<
[2, 4, 7, 13, 15],
[3, 8, 12, 16, 21],
[9, 11, 17, 20, 22],
[10, 18, 19, 23, 24]]</
===Alternative version, inspired by the Common Lisp Alternative Approach===
<
COLS = 9
def CX(x, ran):
Line 4,822 ⟶ 5,377:
print(repr(next(ran[y])).rjust(3), end = ' ')
print()
</syntaxhighlight>
{{out}} COLS = 5 Produces:
<pre>
Line 4,855 ⟶ 5,410:
</pre>
=== Another alternative version ===
<
from __future__ import print_function
Line 4,921 ⟶ 5,476:
if __name__ == '__main__':
main(5)
</syntaxhighlight>
<pre>
zigzag of 5:
Line 4,929 ⟶ 5,484:
9 11 17 20 22
10 18 19 23 24
</pre>
=={{header|Quackery}}==
===Sorting Indices===
{{trans|Python:_By_sorting_indices}}
<syntaxhighlight lang="quackery"> [ ]'[ tuck do dip do ] is with2 ( x x --> x x )
[ dup temp put
[] swap
dup * times [ i^ join ]
sortwith
[ with2
[ temp share /mod
tuck + 1 &
if negate ]
> ]
sortwith
[ with2
[ temp share /mod + ]
> ]
dup witheach
[ i^ unrot poke ]
[] swap
temp share times
[ temp share split
dip [ nested join ] ]
drop
temp release ] is zigzag ( n --> [ )
10 zigzag
witheach
[ witheach
[ dup 10 < if sp
echo sp ]
cr ]</syntaxhighlight>
{{out}}
<pre> 0 1 5 6 14 15 27 28 44 45
2 4 7 13 16 26 29 43 46 63
3 8 12 17 25 30 42 47 62 64
9 11 18 24 31 41 48 61 65 78
10 19 23 32 40 49 60 66 77 79
20 22 33 39 50 59 67 76 80 89
21 34 38 51 58 68 75 81 88 90
35 37 52 57 69 74 82 87 91 96
36 53 56 70 73 83 86 92 95 97
54 55 71 72 84 85 93 94 98 99
</pre>
===Turtle style===
Adapted from [[Spiral matrix#Quackery]]
The sequence of turns for the first half of the matrix is east to southwest to south to northeast to east. In the second half the order of turns is reversed.
<syntaxhighlight lang="quackery"> [ stack ] is stepcount ( --> s )
[ stack ] is position ( --> s )
[ stack ] is heading ( --> s )
[ heading take
behead join
heading put ] is turn ( --> )
[ 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 1 - join
over join
over 1 - negate join
heading put
0 over dup * of
over 1 - times ( turtle draws first half of zigzag )
[ 1 walk turn
i^ 1+ walk turn ]
heading take ( reverse the sequence of turns )
reverse heading put
over 1 - times ( turtle draws second half of zigzag )
[ turn 1 walk
turn i walk ]
1 walk
matrixify ( ...tidy up )
heading release
position release
stepcount release ] is zigzag ( n --> [ )
10 zigzag
witheach
[ witheach
[ dup 10 < if sp echo sp ]
cr ]</syntaxhighlight>
{{out}}
<pre> 0 1 5 6 14 15 27 28 44 45
2 4 7 13 16 26 29 43 46 63
3 8 12 17 25 30 42 47 62 64
9 11 18 24 31 41 48 61 65 78
10 19 23 32 40 49 60 66 77 79
20 22 33 39 50 59 67 76 80 89
21 34 38 51 58 68 75 81 88 90
35 37 52 57 69 74 82 87 91 96
36 53 56 70 73 83 86 92 95 97
54 55 71 72 84 85 93 94 98 99
</pre>
Line 4,936 ⟶ 5,619:
The code can probably be simplified somewhat.
<syntaxhighlight lang="qi">
(define odd? A -> (= 1 (MOD A 2)))
(define even? A -> (= 0 (MOD A 2)))
Line 4,962 ⟶ 5,645:
(range 0 N)))
(range 0 N)))
</syntaxhighlight>
=={{header|R}}==
{{trans|
<
j <- seq(n)
a[i, ] <- v[j + i - 1]
}
}
{{out}}
<pre> [,1] [,2] [,3] [,4] [,5]
[1,] 0 1 5 6 14
[2,] 2 4 7 13 16
[3,] 3 8 12 17 25
[4,] 9 11 18 24 31
[5,] 10 19 23 32 40</pre>
<syntaxhighlight lang="rsplus">zigzag2 <- function(n) {
a <- zigzag1(n)
v <- seq(n - 1)^2
for (i in seq(n - 1)) {
a[n - i + 1, seq(i + 1, n)] <- a[n - i + 1, seq(i + 1, n)] - v[seq(n - i)]
}
a
}
zigzag2(5)</syntaxhighlight>
{{out}}
<pre> [,1] [,2] [,3] [,4] [,5]
[1,] 0 1 5 6 14
[2,] 2 4 7 13 15
[3,] 3 8 12 16 21
[4,] 9 11 17 20 22
[5,] 10 18 19 23 24</pre>
=={{header|Racket}}==
<
#lang racket
Line 5,015 ⟶ 5,716:
(zigzag 4)
</syntaxhighlight>
{{out}}
<pre>
'((0 2 3 9)
(1 4 8 10)
(5 7 11 14)
(6 12 13 15))
</
=={{header|Raku}}==
Line 5,029 ⟶ 5,730:
Using the same Turtle class as in the [[Spiral_matrix#Raku|Spiral matrix]] task:
<syntaxhighlight lang="raku"
my @dv = [0,-1], [1,-1], [1,0], [1,1], [0,1], [-1,1], [-1,0], [-1,-1];
my $points = 8; # 'compass' points of neighbors on grid: north=0, northeast=1, east=2, etc.
Line 5,091 ⟶ 5,792:
}
$t.showmap;
}</
=={{header|Rascal}}==
Line 5,100 ⟶ 5,801:
the key way to understand a zig-zag matrix is to write down
an example with coordinates:
<
2 (1,0), 4 (1,1), 6 (1,2)
5 (2,0), 7 (2,1), 8 (2,2)</
If you order these coordinates on the number, you create the order:
<
One can observe that this increases with the sum of the coordinates,
and secondly with the the first number of the coordinates.
The Rascal example uses this phenomenon:
<
import List;
import Set;
Line 5,135 ⟶ 5,836:
print("<myarray[<y,x>]>\t");}
println();}
}</
{{out}}
<
{0} {1} {3} {6} {10}
{2} {4} {7} {11} {15}
Line 5,143 ⟶ 5,844:
{9} {13} {17} {20} {22}
{14} {18} {21} {23} {24}
ok</
=={{header|REXX}}==
This REXX version allows the optional specification of the '''start''' and '''increment''' values.
===Version 1===
<syntaxhighlight lang="rexx">/*REXX program produces and displays a zig─zag matrix (a square array). */
parse arg n start inc . /*obtain optional arguments from the CL*/
if n=='' | n=="," then n= 5 /*Not specified? Then use the default.*/
Line 5,168 ⟶ 5,870:
do c=2 for n-1; _= _ right(@.r.c, w) /*build a line for output of a row.*/
end /*c*/; say _ /* [↑] align the matrix elements. */
end /*r*/; return</
{{out|output|text= when using the default inputs:}}
<pre>
Line 5,192 ⟶ 5,894:
-1009 -1010 -1014 -1015
</pre>
===Version 2 - simplified logic===
<syntaxhighlight lang="rexx">/*REXX program produces and displays a zig-zag matrix (a square array) */
Parse Arg n start inc . /* obtain optional arguments from command line */
if n=='' | n=="," then n= 5 /*Not specified? use the default*/
if start=='' | start=="," then start= 0 /* " " " " " */
if inc=='' | inc=="," then inc= 1 /* " " " " " */
Parse Value 1 1 n**2 With row col size
Do x=start By inc For size
m.row.col=x
If (row+col)//2=0 Then do /* moving upward */
Select
when row=1 Then Do /* at upper bound */
If col<n Then
col=col+1 /* move right */
Else
row=2 /* move down */
End
when col=n Then /* at right border */
row=row+1 /* move down */
Otherwise Do /* in all other cases */
row=row-1 /* move up */
col=col+1 /* and to the right */
End
End
End
Else Do /* moving downward */
Select
When col=1 Then Do /* at lower bound */
If row=n Then /* in bottom row */
col=2 /* move right */
Else /* otherwise */
row=row+1 /* move down */
End
When row=n Then /* at lower bound */
col=col+1 /* move right */
Otherwise Do /* in all other cases */
row=row+1 /* move down */
col=col-1 /* and to the left */
End
End
End
End
Call show
Exit
/*-----------------------------------------------------------------------*/
show:
w=length(start+size*inc) /* max width of any matrix element */
Do row=1 To n /* loop over rows */
line=right(m.row.1,w) /* first element */
Do column=2 To n /* loop over other elements */
line=line right(m.row.column,w) /* build output line */
End
Say line
End /* display the line */
Return</syntaxhighlight>
=={{header|Ring}}==
<
# Project Zig-zag matrix
Line 5,263 ⟶ 6,021:
exec()
}
</syntaxhighlight>
Output:
[http://kepkezelo.com/images/kk86ng7p4gcl7z3p7vo1.jpg Zig-Zag matrix]
=={{header|RPL}}==
{{works with|RPL|HP-48}}
Turtle's way.
« 1 -1 → n way val
« n DUP 2 →LIST 0 CON
2 n DUP + '''FOR''' s
n s 1 - MIN s OVER -
'''IF''' way 0 > '''THEN''' SWAP '''END'''
'''FOR''' j
j s OVER - 2 →LIST 'val' INCR PUT
way '''STEP'''
'way' SNEG
'''NEXT'''
» » '<span style="color:blue">ZIGZAG</span>' STO
6 <span style="color:blue">ZIGZAG</span>
{{out}}
<pre>
1: [[0 2 3 9 10 20]
[1 4 8 11 19 21]
[5 7 12 18 22 29]
[6 13 17 23 28 30]
[14 16 24 27 31 34]
[15 25 26 32 33 35]]
</pre>
=={{header|Ruby}}==
{{trans|Python}}
<
(seq=*0...n).product(seq)
.sort_by {|x,y| [x+y, (x+y).even? ? y : -y]}
Line 5,281 ⟶ 6,065:
end
print_matrix zigzag(5)</
{{out}}
<pre>
Line 5,289 ⟶ 6,073:
9 11 17 20 22
10 18 19 23 24
</pre>
=={{header|Rust}}==
<syntaxhighlight lang="rust">
use std::cmp::Ordering;
use std::cmp::Ordering::{Equal, Greater, Less};
use std::iter::repeat;
#[derive(Debug, PartialEq, Eq)]
struct SortIndex {
x: usize,
y: usize,
}
impl SortIndex {
fn new(x: usize, y: usize) -> SortIndex {
SortIndex { x, y }
}
}
impl PartialOrd for SortIndex {
fn partial_cmp(&self, other: &SortIndex) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for SortIndex {
fn cmp(&self, other: &SortIndex) -> Ordering {
let lower = if self.x + self.y == other.x + other.y {
if (self.x + self.y) % 2 == 0 {
self.x < other.x
} else {
self.y < other.y
}
} else {
(self.x + self.y) < (other.x + other.y)
};
if lower {
Less
} else if self == other {
Equal
} else {
Greater
}
}
}
fn zigzag(n: usize) -> Vec<Vec<usize>> {
let mut l: Vec<SortIndex> = (0..n * n).map(|i| SortIndex::new(i % n, i / n)).collect();
l.sort();
let init_vec = vec![0; n];
let mut result: Vec<Vec<usize>> = repeat(init_vec).take(n).collect();
for (i, &SortIndex { x, y }) in l.iter().enumerate() {
result[y][x] = i
}
result
}
fn main() {
println!("{:?}", zigzag(5));
}
</syntaxhighlight>
{{out}}
<pre>
[[0, 1, 5, 6, 14], [2, 4, 7, 13, 15], [3, 8, 12, 16, 21], [9, 11, 17, 20, 22], [10, 18, 19, 23, 24]]
</pre>
Line 5,294 ⟶ 6,146:
Uses the array indices sort solution used by others here.
<
val l = for (i <- 0 until n*n) yield (i%n, i/n)
val lSorted = l.sortWith {
Line 5,312 ⟶ 6,164:
ar => ar.foreach(x => print("%3d".format(x)))
println
}</
Output:
<
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
</
=={{header|Scilab}}==
{{trans|Octave}}
<syntaxhighlight lang="scilab">function a = zigzag3(n)
a = zeros(n, n)
for k=1:n
Line 5,342 ⟶ 6,194:
3. 8. 12. 16. 21.
9. 11. 17. 20. 22.
10. 18. 19. 23. 24.</
=={{header|Seed7}}==
<
const type: matrix is array array integer;
Line 5,389 ⟶ 6,241:
writeln;
end for;
end func;</
{{out}}
Line 5,404 ⟶ 6,256:
=={{header|Sidef}}==
{{trans|Perl}}
<
var r = []
Line 5,424 ⟶ 6,276:
}
zig_zag(5, 5).each { say .join('', {|i| "%4i" % i}) }</
{{out}}
<pre>
Line 5,435 ⟶ 6,287:
=={{header|Standard ML}}==
<
print "\n");
fun zig lst M = List.app rowprint (lst M);
Line 5,451 ⟶ 6,303:
)));
zig zag 5 ;</
0 1 5 6 14
2 4 7 13 15
Line 5,464 ⟶ 6,316:
The requested zig-zag matrix can be constructed as a correction of another zig-zag matrix, which is a square "view" of the infinite zig-zag matrix. Here is the latter:
<
j = 0::n-1
u = J(1, n, (-1, 1))
Line 5,485 ⟶ 6,337:
4 | 9 11 18 24 31 |
5 | 10 19 23 32 40 |
+--------------------------+</
Now the corrected matrix, which solves the task:
<
a = zigzag1(n)
v = (1..n-1):^2
Line 5,506 ⟶ 6,358:
4 | 9 11 17 20 22 |
5 | 10 18 19 23 24 |
+--------------------------+</
The correction is given by the difference:
<
[symmetric]
1 2 3 4 5
Line 5,519 ⟶ 6,371:
4 | 0 0 1 4 |
5 | 0 1 4 9 16 |
+--------------------------+</
=={{header|Tcl}}==
Using <code>print_matrix</code> from [[Matrix Transpose#Tcl|Matrix Transpose]]…
<
set m [lrepeat $size [lrepeat $size .]]
set x 0; set dx -1
Line 5,558 ⟶ 6,410:
}
print_matrix [zigzag 5]</
{{out}}
<pre> 0 1 5 6 14
Line 5,568 ⟶ 6,420:
=={{header|uBasic/4tH}}==
{{trans|BBC BASIC}}
<syntaxhighlight lang="ubasic">S = 5
i = 1
Line 5,606 ⟶ 6,458:
Next
Print
Next</
{{out}}
<pre> 0 1 5 6 14
Line 5,618 ⟶ 6,470:
=={{header|Ursala}}==
adapted from the J solution
<
#import nat
zigzag = ~&mlPK2xnSS+ num+ ==+sum~~|=xK9xSL@iiK0+ iota</
test program (three examples):
<
tests = zigzag* <4,5,6></
{{out}}
<pre><
Line 5,648 ⟶ 6,500:
=={{header|VBA}}==
<
Public Sub zigzag(n)
Dim a() As Integer
Line 5,708 ⟶ 6,560:
Next
End Sub
</syntaxhighlight>
{{out}}
Line 5,732 ⟶ 6,584:
=={{header|VBScript}}==
{{trans|BBC BASIC}}
<
Function ZigZag(n)
Line 5,767 ⟶ 6,619:
WScript.StdOut.WriteLine
Next
End Function</
{{out}}
Line 5,791 ⟶ 6,643:
{{trans|Go}}
{{libheader|Wren-fmt}}
<
var zigzag = Fn.new { |n|
Line 5,823 ⟶ 6,675:
if (i%n == n - 1) System.print()
i = i + 1
}</
{{out}}
Line 5,835 ⟶ 6,687:
=={{header|XPL0}}==
<
def N=6;
int A(N,N), X, Y, I, D;
Line 5,857 ⟶ 6,709:
CrLf(0);
];
]</
{{out}}
Line 5,870 ⟶ 6,722:
=={{header|Yabasic}}==
<
DIM array(Size-1, Size-1)
Line 5,891 ⟶ 6,743:
NEXT col
PRINT
NEXT row</
=={{header|zkl}}==
{{trans|Groovy}}
<
grid := (0).pump(n,List, (0).pump(n,List).copy).copy();
ri := Ref(0);
Line 5,905 ⟶ 6,757:
}
grid.pump(String,'wrap(r){("%3s"*n+"\n").fmt(r.xplode())});
}</
{{trans|C}}
Using list comprehension (and side effects) for the double loop,
the resulting list is just thrown away,
which is easier than creating an enumerated list and sorting.
<
s := (0).pump(m*m,List).copy(); // copy to make writable
rn := Ref(0);
Line 5,916 ⟶ 6,768:
'{ s[ if(i.isOdd) j*(m-1)+i else (i-j)*m+j ] = rn.inc(); }]];
s.pump(String,T(Void.Read,m-1), ("%3s"*m+"\n").fmt);
}</
To be pedantic, the same as above,
but using the output of the list comprehension:
<
rn := Ref(0);
[[(i,j); [0..m*2-1]; '{[(0).max(i-m+1) .. i.min(m-1)]};
Line 5,925 ⟶ 6,777:
.sort(fcn([(a,_)], [(b,_)]){ a<b }).apply("get",1)
.pump(String,T(Void.Read,m-1), ("%3s"*m+"\n").fmt);
}</
{{out}} The results are the same:
<pre>
|