Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
3
Task/Zig-zag-matrix/00-META.yaml
Normal file
3
Task/Zig-zag-matrix/00-META.yaml
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
---
|
||||
from: http://rosettacode.org/wiki/Zig-zag_matrix
|
||||
note: Matrices
|
||||
30
Task/Zig-zag-matrix/00-TASK.txt
Normal file
30
Task/Zig-zag-matrix/00-TASK.txt
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
;Task:
|
||||
Produce a zig-zag array.
|
||||
|
||||
|
||||
A ''zig-zag'' array is a square arrangement of the first <big>N<sup>2</sup></big> natural numbers, where the
|
||||
<br>numbers increase sequentially as you zig-zag along the array's [https://en.wiktionary.org/wiki/antidiagonal anti-diagonals].
|
||||
|
||||
For a graphical representation, see [[wp:Image:JPEG_ZigZag.svg|JPG zigzag]] (JPG uses such arrays to encode images).
|
||||
|
||||
|
||||
For example, given '''5''', produce this array:
|
||||
<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>
|
||||
|
||||
|
||||
;Related tasks:
|
||||
* [[Spiral matrix]]
|
||||
* [[Identity matrix]]
|
||||
* [[Ulam spiral (for primes)]]
|
||||
|
||||
|
||||
;See also:
|
||||
* Wiktionary entry: [https://en.wiktionary.org/wiki/antidiagonal anti-diagonals]
|
||||
<br><br>
|
||||
|
||||
13
Task/Zig-zag-matrix/11l/zig-zag-matrix.11l
Normal file
13
Task/Zig-zag-matrix/11l/zig-zag-matrix.11l
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
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))
|
||||
81
Task/Zig-zag-matrix/360-Assembly/zig-zag-matrix.360
Normal file
81
Task/Zig-zag-matrix/360-Assembly/zig-zag-matrix.360
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
* Zig-zag matrix 15/08/2015
|
||||
ZIGZAGMA CSECT
|
||||
USING ZIGZAGMA,R12 set base register
|
||||
LR R12,R15 establish addressability
|
||||
LA R9,N n : matrix size
|
||||
LA R6,1 i=1
|
||||
LA R7,1 j=1
|
||||
LR R11,R9 n
|
||||
MR R10,R9 *n
|
||||
BCTR R11,0 R11=n**2-1
|
||||
SR R8,R8 k=0
|
||||
LOOPK CR R8,R11 do k=0 to n**2-1
|
||||
BH ELOOPK k>limit
|
||||
LR R1,R6 i
|
||||
BCTR R1,0 -1
|
||||
MR R0,R9 *n
|
||||
LR R2,R7 j
|
||||
BCTR R2,0 -1
|
||||
AR R1,R2 (i-1)*n+(j-1)
|
||||
SLA R1,1 index=((i-1)*n+j-1)*2
|
||||
STH R8,T(R1) t(i,j)=k
|
||||
LR R2,R6 i
|
||||
AR R2,R7 i+j
|
||||
LA R1,2 2
|
||||
SRDA R2,32 shift right r1 to r2
|
||||
DR R2,R1 (i+j)/2
|
||||
LTR R2,R2 if mod(i+j,2)=0
|
||||
BNZ ELSEMOD
|
||||
CR R7,R9 if j<n
|
||||
BNL ELSE1
|
||||
LA R7,1(R7) j=j+1
|
||||
B EIF1
|
||||
ELSE1 LA R6,2(R6) i=i+2
|
||||
EIF1 CH R6,=H'1' if i>1
|
||||
BNH NOT1
|
||||
BCTR R6,0 i=i-1
|
||||
NOT1 B NOT2
|
||||
ELSEMOD CR R6,R9 if i<n
|
||||
BNL ELSE2
|
||||
LA R6,1(R6) i=i+1
|
||||
B EIF2
|
||||
ELSE2 LA R7,2(R7) j=j+2
|
||||
EIF2 CH R7,=H'1' if j>1
|
||||
BNH NOT2
|
||||
BCTR R7,0 j=j-1
|
||||
NOT2 LA R8,1(R8) k=k+1
|
||||
B LOOPK
|
||||
ELOOPK LA R6,1 end k; i=1
|
||||
LOOPI CR R6,R9 do i=1 to n
|
||||
BH ELOOPI i>n
|
||||
LA R10,0 ibuf=0 buffer index
|
||||
MVC BUFFER,=CL80' '
|
||||
LA R7,1 j=1
|
||||
LOOPJ CR R7,R9 do j=1 to n
|
||||
BH ELOOPJ j>n
|
||||
LR R1,R6 i
|
||||
BCTR R1,0 -1
|
||||
MR R0,R9 *n
|
||||
LR R2,R7 j
|
||||
BCTR R2,0 -1
|
||||
AR R1,R2 (i-1)*n+(j-1)
|
||||
SLA R1,1 index=((i-1)*n+j-1)*2
|
||||
LH R2,T(R1) t(i,j)
|
||||
LA R3,BUFFER
|
||||
AR R3,R10
|
||||
XDECO R2,XDEC edit t(i,j) length=12
|
||||
MVC 0(4,R3),XDEC+8 move in buffer length=4
|
||||
LA R10,4(R10) ibuf=ibuf+1
|
||||
LA R7,1(R7) j=j+1
|
||||
B LOOPJ
|
||||
ELOOPJ XPRNT BUFFER,80 end j
|
||||
LA R6,1(R6) i=i+1
|
||||
B LOOPI
|
||||
ELOOPI XR R15,R15 end i; return_code=0
|
||||
BR R14 return to caller
|
||||
N EQU 5 matrix size
|
||||
BUFFER DS CL80
|
||||
XDEC DS CL12
|
||||
T DS (N*N)H t(n,n) matrix
|
||||
YREGS
|
||||
END ZIGZAGMA
|
||||
37
Task/Zig-zag-matrix/ALGOL-68/zig-zag-matrix.alg
Normal file
37
Task/Zig-zag-matrix/ALGOL-68/zig-zag-matrix.alg
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
PROC zig zag = (INT n)[,]INT: (
|
||||
PROC move = (REF INT i, j)VOID: (
|
||||
IF j < n THEN
|
||||
i := ( i <= 1 | 1 | i-1 );
|
||||
j +:= 1
|
||||
ELSE
|
||||
i +:= 1
|
||||
FI
|
||||
);
|
||||
|
||||
[n, n]INT a;
|
||||
INT x:=LWB a, y:=LWB a;
|
||||
|
||||
FOR v FROM 0 TO n**2-1 DO
|
||||
a[y, x] := v;
|
||||
IF ODD (x + y) THEN
|
||||
move(x, y)
|
||||
ELSE
|
||||
move(y, x)
|
||||
FI
|
||||
OD;
|
||||
a
|
||||
);
|
||||
|
||||
INT dim = 5;
|
||||
#IF formatted transput possible THEN
|
||||
FORMAT d = $z-d$;
|
||||
FORMAT row = $"("n(dim-1)(f(d)",")f(d)")"$;
|
||||
FORMAT block = $"("n(dim-1)(f(row)","lx)f(row)")"l$;
|
||||
|
||||
printf((block, zig zag(dim)))
|
||||
ELSE#
|
||||
[,]INT result = zig zag(dim);
|
||||
FOR i TO dim DO
|
||||
print((result[i,], new line))
|
||||
OD
|
||||
#FI#
|
||||
58
Task/Zig-zag-matrix/ALGOL-W/zig-zag-matrix.alg
Normal file
58
Task/Zig-zag-matrix/ALGOL-W/zig-zag-matrix.alg
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
begin % zig-zag matrix %
|
||||
% z is returned holding a zig-zag matrix of order n, z must be at least n x n %
|
||||
procedure makeZigZag ( integer value n
|
||||
; integer array z( *, * )
|
||||
) ;
|
||||
begin
|
||||
procedure move ;
|
||||
begin
|
||||
if y = n then begin
|
||||
upRight := not upRight;
|
||||
x := x + 1
|
||||
end
|
||||
else if x = 1 then begin
|
||||
upRight := not upRight;
|
||||
y := y + 1
|
||||
end
|
||||
else begin
|
||||
x := x - 1;
|
||||
y := y + 1
|
||||
end
|
||||
end move ;
|
||||
procedure swapXY ;
|
||||
begin
|
||||
integer swap;
|
||||
swap := x;
|
||||
x := y;
|
||||
y := swap;
|
||||
end swapXY ;
|
||||
integer x, y;
|
||||
logical upRight;
|
||||
% initialise the n x n matrix in z %
|
||||
for i := 1 until n do for j := 1 until n do z( i, j ) := 0;
|
||||
% fill in the zig-zag matrix %
|
||||
x := y := 1;
|
||||
upRight := true;
|
||||
for i := 1 until n * n do begin
|
||||
z( x, y ) := i - 1;
|
||||
if upRight then move
|
||||
else begin
|
||||
swapXY;
|
||||
move;
|
||||
swapXY
|
||||
end;
|
||||
end;
|
||||
end makeZigZap ;
|
||||
|
||||
begin
|
||||
integer array zigZag( 1 :: 10, 1 :: 10 );
|
||||
for n := 5 do begin
|
||||
makeZigZag( n, zigZag );
|
||||
for i := 1 until n do begin
|
||||
write( i_w := 4, s_w := 1, zigZag( i, 1 ) );
|
||||
for j := 2 until n do writeon( i_w := 4, s_w := 1, zigZag( i, j ) );
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
end.
|
||||
8
Task/Zig-zag-matrix/APL/zig-zag-matrix.apl
Normal file
8
Task/Zig-zag-matrix/APL/zig-zag-matrix.apl
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
zz ← {⍵⍴⎕IO-⍨⍋⊃,/{(2|⍴⍵):⌽⍵⋄⍵}¨(⊂w)/¨⍨w{↓⍵∘.=⍨∪⍵}+/[1]⍵⊤w←⎕IO-⍨⍳×/⍵} ⍝ General zigzag (any rectangle)
|
||||
zzSq ← {zz,⍨⍵} ⍝ Square zigzag
|
||||
zzSq 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
|
||||
62
Task/Zig-zag-matrix/ATS/zig-zag-matrix.ats
Normal file
62
Task/Zig-zag-matrix/ATS/zig-zag-matrix.ats
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
(* ****** ****** *)
|
||||
//
|
||||
#include
|
||||
"share/atspre_define.hats" // defines some names
|
||||
#include
|
||||
"share/atspre_staload.hats" // for targeting C
|
||||
#include
|
||||
"share/HATS/atspre_staload_libats_ML.hats" // for ...
|
||||
//
|
||||
(* ****** ****** *)
|
||||
//
|
||||
extern
|
||||
fun
|
||||
Zig_zag_matrix(n: int): void
|
||||
//
|
||||
(* ****** ****** *)
|
||||
|
||||
fun max(a: int, b: int): int =
|
||||
if a > b then a else b
|
||||
|
||||
fun movex(n: int, x: int, y: int): int =
|
||||
if y < n-1 then max(0, x-1) else x+1
|
||||
|
||||
fun movey(n: int, x: int, y: int): int =
|
||||
if y < n-1 then y+1 else y
|
||||
|
||||
fun zigzag(n: int, i: int, row: int, x: int, y: int): void =
|
||||
if i = n*n then ()
|
||||
else
|
||||
let
|
||||
val () = (if x = row then begin print i; print ','; end else ())
|
||||
//val () = (begin print x; print ' '; print y; print ' '; print i; print ' '; end)
|
||||
val nextX: int = if ((x+y) % 2) = 0 then movex(n, x, y) else movey(n, y, x)
|
||||
val nextY: int = if ((x+y) % 2) = 0 then movey(n, x, y) else movex(n, y, x)
|
||||
in
|
||||
zigzag(n, i+1, row, nextX, nextY)
|
||||
end
|
||||
|
||||
implement
|
||||
Zig_zag_matrix(n) =
|
||||
let
|
||||
fun loop(row: int): void =
|
||||
if row = n then () else
|
||||
let
|
||||
val () = zigzag(n, 0, row, 0, 0)
|
||||
val () = println!(" ")
|
||||
in
|
||||
loop(row + 1)
|
||||
end
|
||||
in
|
||||
loop(0)
|
||||
end
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement
|
||||
main0() = () where
|
||||
{
|
||||
val () = Zig_zag_matrix(5)
|
||||
} (* end of [main0] *)
|
||||
|
||||
(* ****** ****** *)
|
||||
28
Task/Zig-zag-matrix/AWK/zig-zag-matrix.awk
Normal file
28
Task/Zig-zag-matrix/AWK/zig-zag-matrix.awk
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
# syntax: GAWK -f ZIG-ZAG_MATRIX.AWK [-v offset={0|1}] [size]
|
||||
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) }
|
||||
width = length(size ^ 2 - 1 + offset) + 1
|
||||
i = j = 1
|
||||
for (n=0; n<=size^2-1; n++) { # build array
|
||||
arr[i-1,j-1] = n + offset
|
||||
if ((i+j) % 2 == 0) {
|
||||
if (j < size) { j++ } else { i+=2 }
|
||||
if (i > 1) { i-- }
|
||||
}
|
||||
else {
|
||||
if (i < size) { i++ } else { j+=2 }
|
||||
if (j > 1) { j-- }
|
||||
}
|
||||
}
|
||||
for (row=0; row<size; row++) { # show array
|
||||
for (col=0; col<size; col++) {
|
||||
printf("%*d",width,arr[row,col])
|
||||
}
|
||||
printf("\n")
|
||||
}
|
||||
exit(0)
|
||||
}
|
||||
63
Task/Zig-zag-matrix/Action-/zig-zag-matrix.action
Normal file
63
Task/Zig-zag-matrix/Action-/zig-zag-matrix.action
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
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
|
||||
37
Task/Zig-zag-matrix/ActionScript/zig-zag-matrix.as
Normal file
37
Task/Zig-zag-matrix/ActionScript/zig-zag-matrix.as
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
package
|
||||
{
|
||||
public class ZigZagMatrix extends Array
|
||||
{
|
||||
|
||||
private var height:uint;
|
||||
private var width:uint;
|
||||
public var mtx:Array = [];
|
||||
|
||||
public function ZigZagMatrix(size:uint)
|
||||
{
|
||||
this.height = size;
|
||||
this.width = size;
|
||||
|
||||
this.mtx = [];
|
||||
for (var i:uint = 0; i < size; i++) {
|
||||
this.mtx[i] = [];
|
||||
}
|
||||
i = 1;
|
||||
var j:uint = 1;
|
||||
for (var e:uint = 0; e < size*size; e++) {
|
||||
this.mtx[i-1][j-1] = e;
|
||||
if ((i + j) % 2 == 0) {
|
||||
// Even stripes
|
||||
if (j < size) j ++;
|
||||
else i += 2;
|
||||
if (i > 1) i --;
|
||||
} else {
|
||||
// Odd stripes
|
||||
if (i < size) i ++;
|
||||
else j += 2;
|
||||
if (j > 1) j --;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
50
Task/Zig-zag-matrix/Ada/zig-zag-matrix.ada
Normal file
50
Task/Zig-zag-matrix/Ada/zig-zag-matrix.ada
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
with Ada.Text_IO; use Ada.Text_IO;
|
||||
|
||||
procedure Test_Zig_Zag is
|
||||
|
||||
type Matrix is array (Positive range <>, Positive range <>) of Natural;
|
||||
function Zig_Zag (Size : Positive) return Matrix is
|
||||
Data : Matrix (1..Size, 1..Size);
|
||||
I, J : Integer := 1;
|
||||
begin
|
||||
Data (1, 1) := 0;
|
||||
for Element in 1..Size**2 - 1 loop
|
||||
if (I + J) mod 2 = 0 then
|
||||
-- Even stripes
|
||||
if J < Size then
|
||||
J := J + 1;
|
||||
else
|
||||
I := I + 2;
|
||||
end if;
|
||||
if I > 1 then
|
||||
I := I - 1;
|
||||
end if;
|
||||
else
|
||||
-- Odd stripes
|
||||
if I < Size then
|
||||
I := I + 1;
|
||||
else
|
||||
J := J + 2;
|
||||
end if;
|
||||
if J > 1 then
|
||||
J := J - 1;
|
||||
end if;
|
||||
end if;
|
||||
Data (I, J) := Element;
|
||||
end loop;
|
||||
return Data;
|
||||
end Zig_Zag;
|
||||
|
||||
procedure Put (Data : Matrix) is
|
||||
begin
|
||||
for I in Data'Range (1) loop
|
||||
for J in Data'Range (2) loop
|
||||
Put (Integer'Image (Data (I, J)));
|
||||
end loop;
|
||||
New_Line;
|
||||
end loop;
|
||||
end Put;
|
||||
|
||||
begin
|
||||
Put (Zig_Zag (5));
|
||||
end Test_Zig_Zag;
|
||||
48
Task/Zig-zag-matrix/Agena/zig-zag-matrix.agena
Normal file
48
Task/Zig-zag-matrix/Agena/zig-zag-matrix.agena
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
# zig-zag matrix
|
||||
|
||||
makeZigZag := proc( n :: number ) :: table is
|
||||
|
||||
local move := proc( x :: number, y :: number, upRight :: boolean ) is
|
||||
if y = n then
|
||||
upRight := not upRight;
|
||||
x := x + 1
|
||||
elif x = 1 then
|
||||
upRight := not upRight;
|
||||
y := y + 1
|
||||
else
|
||||
x := x - 1;
|
||||
y := y + 1
|
||||
fi;
|
||||
return x, y, upRight
|
||||
end ;
|
||||
|
||||
# create empty table
|
||||
local result := [];
|
||||
for i to n do
|
||||
result[ i ] := [];
|
||||
for j to n do result[ i, j ] := 0 od
|
||||
od;
|
||||
|
||||
# fill the table
|
||||
local x, y, upRight := 1, 1, true;
|
||||
for i to n * n do
|
||||
result[ x, y ] := i - 1;
|
||||
if upRight then
|
||||
x, y, upRight := move( x, y, upRight )
|
||||
else
|
||||
y, x, upRight := move( y, x, upRight )
|
||||
fi
|
||||
od;
|
||||
|
||||
return result
|
||||
end;
|
||||
|
||||
scope
|
||||
local m := makeZigZag( 5 );
|
||||
for i to size m do
|
||||
for j to size m do
|
||||
printf( " %3d", m[ i, j ] )
|
||||
od;
|
||||
print()
|
||||
od
|
||||
epocs
|
||||
37
Task/Zig-zag-matrix/AppleScript/zig-zag-matrix-1.applescript
Normal file
37
Task/Zig-zag-matrix/AppleScript/zig-zag-matrix-1.applescript
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
set n to 5 -- Size of zig-zag matrix (n^2 cells).
|
||||
|
||||
-- Create an empty matrix.
|
||||
set m to {}
|
||||
repeat with i from 1 to n
|
||||
set R to {}
|
||||
repeat with j from 1 to n
|
||||
set end of R to 0
|
||||
end repeat
|
||||
set end of m to R
|
||||
end repeat
|
||||
|
||||
-- Populate the matrix in a zig-zag manner.
|
||||
set {x, y, v, d} to {1, 1, 0, 1}
|
||||
repeat while v < (n ^ 2)
|
||||
if 1 ≤ x and x ≤ n and 1 ≤ y and y ≤ n then
|
||||
set {m's item y's item x, x, y, v} to {v, x + d, y - d, v + 1}
|
||||
else if x > n then
|
||||
set {x, y, d} to {n, y + 2, -d}
|
||||
else if y > n then
|
||||
set {x, y, d} to {x + 2, n, -d}
|
||||
else if x < 1 then
|
||||
set {x, y, d} to {1, y, -d}
|
||||
else if y < 1 then
|
||||
set {x, y, d} to {x, 1, -d}
|
||||
end if
|
||||
end repeat
|
||||
--> R = {{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}}
|
||||
|
||||
-- Reformat the matrix into a table for viewing.
|
||||
repeat with i in m
|
||||
repeat with j in i
|
||||
set j's contents to (characters -(length of (n ^ 2 as string)) thru -1 of (" " & j)) as string
|
||||
end repeat
|
||||
set end of i to return
|
||||
end repeat
|
||||
return return & m as string
|
||||
34
Task/Zig-zag-matrix/AppleScript/zig-zag-matrix-2.applescript
Normal file
34
Task/Zig-zag-matrix/AppleScript/zig-zag-matrix-2.applescript
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
set n to 5
|
||||
|
||||
set m to {}
|
||||
repeat with i from 1 to n
|
||||
set end of m to {} -- Built a foundation for the matrix out of n empty lists.
|
||||
end repeat
|
||||
|
||||
set {v, d, i} to {0, -1, 1}
|
||||
repeat while v < n ^ 2
|
||||
if length of m's item i < n then
|
||||
set {end of m's item i, i, v} to {f(v, n), i + d, v + 1}
|
||||
if i < 1 then
|
||||
set {i, d} to {1, -d}
|
||||
else if i > n then
|
||||
set {i, d} to {n, -d}
|
||||
else if i > 1 and (count of m's item (i - 1)) = 1 then
|
||||
set d to -d
|
||||
end if
|
||||
else
|
||||
set {i, d} to {i + 1, 1}
|
||||
end if
|
||||
end repeat
|
||||
|
||||
-- Handler/function to format the cells on the fly.
|
||||
on f(v, n)
|
||||
return (characters -(length of (n ^ 2 as string)) thru -1 of (" " & v)) as string
|
||||
end f
|
||||
|
||||
-- Reformat the matrix into a table for viewing.
|
||||
set text item delimiters to ""
|
||||
repeat with i in m
|
||||
set i's contents to (i as string) & return
|
||||
end repeat
|
||||
return return & m as string
|
||||
158
Task/Zig-zag-matrix/AppleScript/zig-zag-matrix-3.applescript
Normal file
158
Task/Zig-zag-matrix/AppleScript/zig-zag-matrix-3.applescript
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
-- zigzagMatrix
|
||||
on zigzagMatrix(n)
|
||||
|
||||
-- diagonals :: n -> [[n]]
|
||||
script diagonals
|
||||
on |λ|(n)
|
||||
script mf
|
||||
on diags(xs, iCol, iRow)
|
||||
if (iCol < length of xs) then
|
||||
if iRow < n then
|
||||
set iNext to iCol + 1
|
||||
else
|
||||
set iNext to iCol - 1
|
||||
end if
|
||||
|
||||
set {headList, tail} to splitAt(iCol, xs)
|
||||
{headList} & diags(tail, iNext, iRow + 1)
|
||||
else
|
||||
{xs}
|
||||
end if
|
||||
end diags
|
||||
end script
|
||||
|
||||
diags(enumFromTo(0, n * n - 1), 1, 1) of mf
|
||||
end |λ|
|
||||
end script
|
||||
|
||||
-- oddReversed :: [a] -> Int -> [a]
|
||||
script oddReversed
|
||||
on |λ|(lst, i)
|
||||
if i mod 2 = 0 then
|
||||
lst
|
||||
else
|
||||
reverse of lst
|
||||
end if
|
||||
end |λ|
|
||||
end script
|
||||
|
||||
rowsFromDiagonals(n, map(oddReversed, |λ|(n) of diagonals))
|
||||
|
||||
end zigzagMatrix
|
||||
|
||||
-- Rows of given length from list of diagonals
|
||||
-- rowsFromDiagonals :: Int -> [[a]] -> [[a]]
|
||||
on rowsFromDiagonals(n, lst)
|
||||
if length of lst > 0 then
|
||||
|
||||
-- lengthOverOne :: [a] -> Bool
|
||||
script lengthOverOne
|
||||
on |λ|(lst)
|
||||
length of lst > 1
|
||||
end |λ|
|
||||
end script
|
||||
|
||||
set {edge, residue} to splitAt(n, lst)
|
||||
|
||||
{map(my head, edge)} & ¬
|
||||
rowsFromDiagonals(n, ¬
|
||||
map(my tail, ¬
|
||||
filter(lengthOverOne, edge)) & residue)
|
||||
else
|
||||
{}
|
||||
end if
|
||||
end rowsFromDiagonals
|
||||
|
||||
|
||||
-- TEST -----------------------------------------------------------------------
|
||||
on run
|
||||
|
||||
zigzagMatrix(5)
|
||||
|
||||
end run
|
||||
|
||||
|
||||
-- GENERIC FUNCTIONS ----------------------------------------------------------
|
||||
|
||||
-- enumFromTo :: Int -> Int -> [Int]
|
||||
on enumFromTo(m, n)
|
||||
if n < m then
|
||||
set d to -1
|
||||
else
|
||||
set d to 1
|
||||
end if
|
||||
set lst to {}
|
||||
repeat with i from m to n by d
|
||||
set end of lst to i
|
||||
end repeat
|
||||
return lst
|
||||
end enumFromTo
|
||||
|
||||
-- filter :: (a -> Bool) -> [a] -> [a]
|
||||
on filter(f, xs)
|
||||
tell mReturn(f)
|
||||
set lst to {}
|
||||
set lng to length of xs
|
||||
repeat with i from 1 to lng
|
||||
set v to item i of xs
|
||||
if |λ|(v, i, xs) then set end of lst to v
|
||||
end repeat
|
||||
return lst
|
||||
end tell
|
||||
end filter
|
||||
|
||||
-- head :: [a] -> a
|
||||
on head(xs)
|
||||
if length of xs > 0 then
|
||||
item 1 of xs
|
||||
else
|
||||
missing value
|
||||
end if
|
||||
end head
|
||||
|
||||
-- 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
|
||||
|
||||
-- Lift 2nd class handler function into 1st class script wrapper
|
||||
-- mReturn :: Handler -> Script
|
||||
on mReturn(f)
|
||||
if class of f is script then
|
||||
f
|
||||
else
|
||||
script
|
||||
property |λ| : f
|
||||
end script
|
||||
end if
|
||||
end mReturn
|
||||
|
||||
-- splitAt:: n -> list -> {n items from start of list, rest of list}
|
||||
-- splitAt :: Int -> [a] -> ([a], [a])
|
||||
on splitAt(n, xs)
|
||||
if n > 0 and n < length of xs then
|
||||
{items 1 thru n of xs, items (n + 1) thru -1 of xs}
|
||||
else
|
||||
if n < 1 then
|
||||
{{}, xs}
|
||||
else
|
||||
{xs, {}}
|
||||
end if
|
||||
end if
|
||||
end splitAt
|
||||
|
||||
-- tail :: [a] -> [a]
|
||||
on tail(xs)
|
||||
if length of xs > 1 then
|
||||
items 2 thru -1 of xs
|
||||
else
|
||||
{}
|
||||
end if
|
||||
end tail
|
||||
65
Task/Zig-zag-matrix/AppleScript/zig-zag-matrix-4.applescript
Normal file
65
Task/Zig-zag-matrix/AppleScript/zig-zag-matrix-4.applescript
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
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
|
||||
25
Task/Zig-zag-matrix/Applesoft-BASIC/zig-zag-matrix.basic
Normal file
25
Task/Zig-zag-matrix/Applesoft-BASIC/zig-zag-matrix.basic
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
100 S = 5
|
||||
110 S2 = S ^ 2 : REM SQUARED
|
||||
120 H = S2 / 2 : REM HALFWAY
|
||||
130 S2 = S2 - 1
|
||||
140 DX = 1 : REM INITIAL
|
||||
150 DY = 0 : REM DIRECTION
|
||||
160 N = S - 1
|
||||
170 DIM A%(N, N)
|
||||
|
||||
200 FOR I = 0 TO H
|
||||
210 A%(X, Y) = I
|
||||
220 A%(N - X, N - Y) = S2 - I
|
||||
230 X = X + DX
|
||||
240 Y = Y + DY
|
||||
250 IF Y = 0 THEN DY = DY + 1 : IF DY THEN DX = -DX
|
||||
260 IF X = 0 THEN DX = DX + 1 : IF DX THEN DY = -DY
|
||||
270 NEXT I
|
||||
|
||||
300 FOR Y = 0 TO N
|
||||
310 FOR X = 0 TO N
|
||||
320 IF X THEN PRINT TAB(X * (LEN(STR$(S2)) + 1) + 1);
|
||||
330 PRINT A%(X, Y);
|
||||
340 NEXT X
|
||||
350 PRINT
|
||||
360 NEXT Y
|
||||
24
Task/Zig-zag-matrix/Arturo/zig-zag-matrix.arturo
Normal file
24
Task/Zig-zag-matrix/Arturo/zig-zag-matrix.arturo
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
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]
|
||||
21
Task/Zig-zag-matrix/AutoHotkey/zig-zag-matrix.ahk
Normal file
21
Task/Zig-zag-matrix/AutoHotkey/zig-zag-matrix.ahk
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
n = 5 ; size
|
||||
v := x := y := 1 ; initial values
|
||||
Loop % n*n { ; for every array element
|
||||
a_%x%_%y% := v++ ; assign the next index
|
||||
If ((x+y)&1) ; odd diagonal
|
||||
If (x < n) ; while inside the square
|
||||
y -= y<2 ? 0 : 1, x++ ; move right-up
|
||||
Else y++ ; on the edge increment y, but not x: to even diagonal
|
||||
Else ; even diagonal
|
||||
If (y < n) ; while inside the square
|
||||
x -= x<2 ? 0 : 1, y++ ; move left-down
|
||||
Else x++ ; on the edge increment x, but not y: to odd diagonal
|
||||
}
|
||||
|
||||
Loop %n% { ; generate printout
|
||||
x := A_Index ; for each row
|
||||
Loop %n% ; and for each column
|
||||
t .= a_%x%_%A_Index% "`t" ; attach stored index
|
||||
t .= "`n" ; row is complete
|
||||
}
|
||||
MsgBox %t% ; show output
|
||||
27
Task/Zig-zag-matrix/AutoIt/zig-zag-matrix.autoit
Normal file
27
Task/Zig-zag-matrix/AutoIt/zig-zag-matrix.autoit
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
#include <Array.au3>
|
||||
$Array = ZigZag(5)
|
||||
_ArrayDisplay($Array)
|
||||
|
||||
Func ZigZag($int)
|
||||
Local $av_array[$int][$int]
|
||||
Local $x = 1, $y = 1
|
||||
For $I = 0 To $int ^ 2 -1
|
||||
$av_array[$x-1][$y-1] = $I
|
||||
If Mod(($x + $y), 2) = 0 Then ;Even
|
||||
if ($y < $int) Then
|
||||
$y += 1
|
||||
Else
|
||||
$x += 2
|
||||
EndIf
|
||||
if ($x > 1) Then $x -= 1
|
||||
Else ; ODD
|
||||
if ($x < $int) Then
|
||||
$x += 1
|
||||
Else
|
||||
$y += 2
|
||||
EndIf
|
||||
If $y > 1 Then $y -= 1
|
||||
EndIf
|
||||
Next
|
||||
Return $av_array
|
||||
EndFunc ;==>ZigZag
|
||||
23
Task/Zig-zag-matrix/BBC-BASIC/zig-zag-matrix.basic
Normal file
23
Task/Zig-zag-matrix/BBC-BASIC/zig-zag-matrix.basic
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
Size% = 5
|
||||
DIM array%(Size%-1,Size%-1)
|
||||
|
||||
i% = 1
|
||||
j% = 1
|
||||
FOR e% = 0 TO Size%^2-1
|
||||
array%(i%-1,j%-1) = e%
|
||||
IF ((i% + j%) AND 1) = 0 THEN
|
||||
IF j% < Size% j% += 1 ELSE i% += 2
|
||||
IF i% > 1 i% -= 1
|
||||
ELSE
|
||||
IF i% < Size% i% += 1 ELSE j% += 2
|
||||
IF j% > 1 j% -= 1
|
||||
ENDIF
|
||||
NEXT
|
||||
|
||||
@% = &904
|
||||
FOR row% = 0 TO Size%-1
|
||||
FOR col% = 0 TO Size%-1
|
||||
PRINT array%(row%,col%);
|
||||
NEXT
|
||||
PRINT
|
||||
NEXT row%
|
||||
2
Task/Zig-zag-matrix/BQN/zig-zag-matrix-1.bqn
Normal file
2
Task/Zig-zag-matrix/BQN/zig-zag-matrix-1.bqn
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
Flip ← {m←2|+⌜˜↕≠𝕩 ⋄ (⍉𝕩׬m)+𝕩×m}
|
||||
Zz ← {Flip ⍋∘⍋⌾⥊+⌜˜↕𝕩}
|
||||
1
Task/Zig-zag-matrix/BQN/zig-zag-matrix-2.bqn
Normal file
1
Task/Zig-zag-matrix/BQN/zig-zag-matrix-2.bqn
Normal file
|
|
@ -0,0 +1 @@
|
|||
Zz 5
|
||||
50
Task/Zig-zag-matrix/Beads/zig-zag-matrix.beads
Normal file
50
Task/Zig-zag-matrix/Beads/zig-zag-matrix.beads
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
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)
|
||||
3
Task/Zig-zag-matrix/Befunge/zig-zag-matrix.bf
Normal file
3
Task/Zig-zag-matrix/Befunge/zig-zag-matrix.bf
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
>> 5 >>00p0010p:1:>20p030pv >0g-:0`*:*-:00g:*1-55+/>\55+/:v v:,*84<
|
||||
v:++!\**2p01:+1g01:g02$$_>>#^4#00#+p#1:#+1#g0#0g#3<^/+ 55\_$:>55+/\|
|
||||
>55+,20g!00g10g`>#^_$$$@^!`g03g00!g04++**2p03:+1g03!\*+1*2g01:g04.$<
|
||||
81
Task/Zig-zag-matrix/C++/zig-zag-matrix.cpp
Normal file
81
Task/Zig-zag-matrix/C++/zig-zag-matrix.cpp
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
#include <vector>
|
||||
#include <memory> // for auto_ptr
|
||||
#include <cmath> // for the 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 > getZigZagArray( int dimension )
|
||||
{
|
||||
auto_ptr< IntTable > zigZagArrayPtr( new IntTable(
|
||||
dimension, IntRow( dimension ) ) );
|
||||
|
||||
// fill along diagonal stripes (oriented as "/")
|
||||
int lastValue = dimension * dimension - 1;
|
||||
int currNum = 0;
|
||||
int currDiag = 0;
|
||||
int loopFrom;
|
||||
int loopTo;
|
||||
int i;
|
||||
int row;
|
||||
int col;
|
||||
do
|
||||
{
|
||||
if ( currDiag < dimension ) // if doing the upper-left triangular half
|
||||
{
|
||||
loopFrom = 0;
|
||||
loopTo = currDiag;
|
||||
}
|
||||
else // doing the bottom-right triangular half
|
||||
{
|
||||
loopFrom = currDiag - dimension + 1;
|
||||
loopTo = dimension - 1;
|
||||
}
|
||||
|
||||
for ( i = loopFrom; i <= loopTo; i++ )
|
||||
{
|
||||
if ( currDiag % 2 == 0 ) // want to fill upwards
|
||||
{
|
||||
row = loopTo - i + loopFrom;
|
||||
col = i;
|
||||
}
|
||||
else // want to fill downwards
|
||||
{
|
||||
row = i;
|
||||
col = loopTo - i + loopFrom;
|
||||
}
|
||||
|
||||
( *zigZagArrayPtr )[ row ][ col ] = currNum++;
|
||||
}
|
||||
|
||||
currDiag++;
|
||||
}
|
||||
while ( currDiag <= lastValue );
|
||||
|
||||
return zigZagArrayPtr;
|
||||
}
|
||||
|
||||
void printZigZagArray( const auto_ptr< IntTable >& zigZagArrayPtr )
|
||||
{
|
||||
size_t dimension = zigZagArrayPtr->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 ) << ( *zigZagArrayPtr )[ row ][ col ];
|
||||
cout << endl;
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
printZigZagArray( getZigZagArray( 5 ) );
|
||||
}
|
||||
25
Task/Zig-zag-matrix/C-sharp/zig-zag-matrix.cs
Normal file
25
Task/Zig-zag-matrix/C-sharp/zig-zag-matrix.cs
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
public static int[,] ZigZag(int n)
|
||||
{
|
||||
int[,] result = new int[n, n];
|
||||
int i = 0, j = 0;
|
||||
int d = -1; // -1 for top-right move, +1 for bottom-left move
|
||||
int start = 0, end = n * n - 1;
|
||||
do
|
||||
{
|
||||
result[i, j] = start++;
|
||||
result[n - i - 1, n - j - 1] = end--;
|
||||
|
||||
i += d; j -= d;
|
||||
if (i < 0)
|
||||
{
|
||||
i++; d = -d; // top reached, reverse
|
||||
}
|
||||
else if (j < 0)
|
||||
{
|
||||
j++; d = -d; // left reached, reverse
|
||||
}
|
||||
} while (start < end);
|
||||
if (start == end)
|
||||
result[i, j] = start;
|
||||
return result;
|
||||
}
|
||||
23
Task/Zig-zag-matrix/C/zig-zag-matrix.c
Normal file
23
Task/Zig-zag-matrix/C/zig-zag-matrix.c
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
int main(int c, char **v)
|
||||
{
|
||||
int i, j, m, n, *s;
|
||||
|
||||
/* default size: 5 */
|
||||
if (c < 2 || ((m = atoi(v[1]))) <= 0) m = 5;
|
||||
|
||||
/* alloc array*/
|
||||
s = malloc(sizeof(int) * m * m);
|
||||
|
||||
for (i = n = 0; i < m * 2; i++)
|
||||
for (j = (i < m) ? 0 : i-m+1; j <= i && j < m; j++)
|
||||
s[(i&1)? j*(m-1)+i : (i-j)*m+j ] = n++;
|
||||
|
||||
for (i = 0; i < m * m; putchar((++i % m) ? ' ':'\n'))
|
||||
printf("%3d", s[i]);
|
||||
|
||||
/* free(s) */
|
||||
return 0;
|
||||
}
|
||||
50
Task/Zig-zag-matrix/Ceylon/zig-zag-matrix.ceylon
Normal file
50
Task/Zig-zag-matrix/Ceylon/zig-zag-matrix.ceylon
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
class ZigZag(Integer size) {
|
||||
|
||||
value data = Array {
|
||||
for (i in 0:size)
|
||||
Array.ofSize(size, 0)
|
||||
};
|
||||
|
||||
variable value i = 1;
|
||||
variable value j = 1;
|
||||
|
||||
for (element in 0 : size^2) {
|
||||
data[j - 1]?.set(i - 1, element);
|
||||
if ((i + j).even) {
|
||||
if (j < size) {
|
||||
j++;
|
||||
}
|
||||
else {
|
||||
i += 2;
|
||||
}
|
||||
if (i > 1) {
|
||||
i--;
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (i < size) {
|
||||
i++;
|
||||
}
|
||||
else {
|
||||
j += 2;
|
||||
}
|
||||
if (j > 1) {
|
||||
j--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
shared void display() {
|
||||
for (row in data) {
|
||||
for (element in row) {
|
||||
process.write(element.string.pad(3));
|
||||
}
|
||||
print(""); //newline
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
shared void run() {
|
||||
value zz = ZigZag(5);
|
||||
zz.display();
|
||||
}
|
||||
33
Task/Zig-zag-matrix/Clojure/zig-zag-matrix.clj
Normal file
33
Task/Zig-zag-matrix/Clojure/zig-zag-matrix.clj
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
(defn partitions [sizes coll]
|
||||
(lazy-seq
|
||||
(when-let [n (first sizes)]
|
||||
(when-let [s (seq coll)]
|
||||
(cons (take n coll)
|
||||
(partitions (next sizes) (drop n coll)))))))
|
||||
|
||||
(defn take-from [n colls]
|
||||
(lazy-seq
|
||||
(when-let [s (seq colls)]
|
||||
(let [[first-n rest-n] (split-at n s)]
|
||||
(cons (map first first-n)
|
||||
(take-from n (concat (filter seq (map rest first-n)) rest-n)))))))
|
||||
|
||||
(defn zig-zag [n]
|
||||
(->> (partitions (concat (range 1 (inc n)) (range (dec n) 0 -1)) (range (* n n)))
|
||||
(map #(%1 %2) (cycle [reverse identity]) ,)
|
||||
(take-from n ,)))
|
||||
|
||||
user> (zig-zag 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))
|
||||
|
||||
user> (zig-zag 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))
|
||||
41
Task/Zig-zag-matrix/CoffeeScript/zig-zag-matrix.coffee
Normal file
41
Task/Zig-zag-matrix/CoffeeScript/zig-zag-matrix.coffee
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
# Calculate a zig-zag pattern of numbers like so:
|
||||
# 0 1 5
|
||||
# 2 4 6
|
||||
# 3 7 8
|
||||
#
|
||||
# There are many interesting ways to solve this; we
|
||||
# try for an algebraic approach, calculating triangle
|
||||
# areas, so that me minimize space requirements.
|
||||
|
||||
zig_zag_value = (x, y, n) ->
|
||||
|
||||
upper_triangle_zig_zag = (x, y) ->
|
||||
# calculate the area of the triangle from the prior
|
||||
# diagonals
|
||||
diag = x + y
|
||||
triangle_area = diag * (diag+1) / 2
|
||||
# then add the offset along the diagonal
|
||||
if diag % 2 == 0
|
||||
triangle_area + y
|
||||
else
|
||||
triangle_area + x
|
||||
|
||||
if x + y < n
|
||||
upper_triangle_zig_zag x, y
|
||||
else
|
||||
# For the bottom right part of the matrix, we essentially
|
||||
# use reflection to count backward.
|
||||
bottom_right_cell = n * n - 1
|
||||
n -= 1
|
||||
v = upper_triangle_zig_zag(n-x, n-y)
|
||||
bottom_right_cell - v
|
||||
|
||||
zig_zag_matrix = (n) ->
|
||||
row = (i) -> (zig_zag_value i, j, n for j in [0...n])
|
||||
(row i for i in [0...n])
|
||||
|
||||
do ->
|
||||
for n in [4..6]
|
||||
console.log "---- n=#{n}"
|
||||
console.log zig_zag_matrix(n)
|
||||
console.log "\n"
|
||||
14
Task/Zig-zag-matrix/Common-Lisp/zig-zag-matrix-1.lisp
Normal file
14
Task/Zig-zag-matrix/Common-Lisp/zig-zag-matrix-1.lisp
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
(defun zigzag (n)
|
||||
(flet ((move (i j)
|
||||
(if (< j (1- n))
|
||||
(values (max 0 (1- i)) (1+ j))
|
||||
(values (1+ i) j))))
|
||||
(loop with a = (make-array (list n n) :element-type 'integer)
|
||||
with x = 0
|
||||
with y = 0
|
||||
for v from 0 below (* n n)
|
||||
do (setf (aref a x y) v)
|
||||
(if (evenp (+ x y))
|
||||
(setf (values x y) (move x y))
|
||||
(setf (values y x) (move y x)))
|
||||
finally (return a))))
|
||||
17
Task/Zig-zag-matrix/Common-Lisp/zig-zag-matrix-2.lisp
Normal file
17
Task/Zig-zag-matrix/Common-Lisp/zig-zag-matrix-2.lisp
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
; ZigZag
|
||||
;
|
||||
; Nigel Galloway.
|
||||
; June 4th., 2012
|
||||
;
|
||||
(defun ZigZag (COLS)
|
||||
(let ((cs 2) (st '(1 2)) (dx '(-1 1)))
|
||||
(defun new_cx (i)
|
||||
(setq st (append st (list (setq cs (+ cs (* 2 i))) (setq cs (+ 1 cs))))
|
||||
dx (append dx '(-1 1))))
|
||||
(do ((i 2 (+ 2 i))) ((>= i COLS)) (new_cx i))
|
||||
(do ((i (- COLS 1 (mod COLS 2)) (+ -2 i))) ((<= i 0)) (new_cx i))
|
||||
(do ((i 0 (+ 1 i))) ((>= i COLS))
|
||||
(format t "~%")
|
||||
(do ((j i (+ 1 j))) ((>= j (+ COLS i)))
|
||||
(format t "~3d" (nth j st))
|
||||
(setf (nth j st) (+ (nth j st) (nth j dx)))))))
|
||||
12
Task/Zig-zag-matrix/Crystal/zig-zag-matrix.crystal
Normal file
12
Task/Zig-zag-matrix/Crystal/zig-zag-matrix.crystal
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
def zigzag(n)
|
||||
(seq=(0...n).to_a).product(seq)
|
||||
.sort_by {|x,y| [x+y, (x+y).even? ? y : -y]}
|
||||
.map_with_index{|v, i| {v, i}}.sort.map(&.last).each_slice(n).to_a
|
||||
end
|
||||
|
||||
def print_matrix(m)
|
||||
format = "%#{m.flatten.max.to_s.size}d " * m[0].size
|
||||
m.each {|row| puts format % row}
|
||||
end
|
||||
|
||||
print_matrix zigzag(5)
|
||||
24
Task/Zig-zag-matrix/D/zig-zag-matrix-1.d
Normal file
24
Task/Zig-zag-matrix/D/zig-zag-matrix-1.d
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
int[][] zigZag(in int n) pure nothrow @safe {
|
||||
static void move(in int n, ref int i, ref int j)
|
||||
pure nothrow @safe @nogc {
|
||||
if (j < n - 1) {
|
||||
if (i > 0) i--;
|
||||
j++;
|
||||
} else
|
||||
i++;
|
||||
}
|
||||
|
||||
auto a = new int[][](n, n);
|
||||
int x, y;
|
||||
foreach (v; 0 .. n ^^ 2) {
|
||||
a[y][x] = v;
|
||||
(x + y) % 2 ? move(n, x, y) : move(n, y, x);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
void main() {
|
||||
import std.stdio;
|
||||
|
||||
writefln("%(%(%2d %)\n%)", 5.zigZag);
|
||||
}
|
||||
18
Task/Zig-zag-matrix/D/zig-zag-matrix-2.d
Normal file
18
Task/Zig-zag-matrix/D/zig-zag-matrix-2.d
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import std.stdio, std.algorithm, std.range, std.array;
|
||||
|
||||
int[][] zigZag(in int n) pure nothrow {
|
||||
static struct P2 { int x, y; }
|
||||
const L = iota(n ^^ 2).map!(i => P2(i % n, i / n)).array
|
||||
.sort!q{ (a.x + a.y == b.x + b.y) ?
|
||||
((a.x + a.y) % 2 ? a.y < b.y : a.x < b.x) :
|
||||
(a.x + a.y) < (b.x + b.y) }.release;
|
||||
|
||||
auto result = new typeof(return)(n, n);
|
||||
foreach (immutable i, immutable p; L)
|
||||
result[p.y][p.x] = i;
|
||||
return result;
|
||||
}
|
||||
|
||||
void main() {
|
||||
writefln("%(%(%2d %)\n%)", 5.zigZag);
|
||||
}
|
||||
56
Task/Zig-zag-matrix/Delphi/zig-zag-matrix.delphi
Normal file
56
Task/Zig-zag-matrix/Delphi/zig-zag-matrix.delphi
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
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;
|
||||
24
Task/Zig-zag-matrix/E/zig-zag-matrix.e
Normal file
24
Task/Zig-zag-matrix/E/zig-zag-matrix.e
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
def zigZag(n) {
|
||||
def move(&i, &j) {
|
||||
if (j < (n - 1)) {
|
||||
i := 0.max(i - 1)
|
||||
j += 1
|
||||
} else {
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
|
||||
def array := makeFlex2DArray(n, n)
|
||||
var x := 0
|
||||
var y := 0
|
||||
|
||||
for i in 1..n**2 {
|
||||
array[y, x] := i
|
||||
if ((x + y) % 2 == 0) {
|
||||
move(&x, &y)
|
||||
} else {
|
||||
move(&y, &x)
|
||||
}
|
||||
}
|
||||
return array
|
||||
}
|
||||
30
Task/Zig-zag-matrix/EMal/zig-zag-matrix.emal
Normal file
30
Task/Zig-zag-matrix/EMal/zig-zag-matrix.emal
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
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))
|
||||
29
Task/Zig-zag-matrix/ERRE/zig-zag-matrix.erre
Normal file
29
Task/Zig-zag-matrix/ERRE/zig-zag-matrix.erre
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
PROGRAM ZIG_ZAG
|
||||
|
||||
!$DYNAMIC
|
||||
DIM ARRAY%[0,0]
|
||||
|
||||
BEGIN
|
||||
SIZE%=5
|
||||
!$DIM ARRAY%[SIZE%-1,SIZE%-1]
|
||||
|
||||
I%=1
|
||||
J%=1
|
||||
FOR E%=0 TO SIZE%^2-1 DO
|
||||
ARRAY%[I%-1,J%-1]=E%
|
||||
IF ((I%+J%) AND 1)=0 THEN
|
||||
IF J%<SIZE% THEN J%+=1 ELSE I%+=2 END IF
|
||||
IF I%>1 THEN I%-=1 END IF
|
||||
ELSE
|
||||
IF I%<SIZE% THEN I%+=1 ELSE J%+=2 END IF
|
||||
IF J%>1 THEN J%-=1 END IF
|
||||
END IF
|
||||
END FOR
|
||||
|
||||
FOR ROW%=0 TO SIZE%-1 DO
|
||||
FOR COL%=0 TO SIZE%-1 DO
|
||||
WRITE("###";ARRAY%[ROW%,COL%];)
|
||||
END FOR
|
||||
PRINT
|
||||
END FOR
|
||||
END PROGRAM
|
||||
44
Task/Zig-zag-matrix/Elena/zig-zag-matrix.elena
Normal file
44
Task/Zig-zag-matrix/Elena/zig-zag-matrix.elena
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import extensions;
|
||||
|
||||
extension op : IntNumber
|
||||
{
|
||||
zigzagMatrix()
|
||||
{
|
||||
auto result := IntMatrix.allocate(self, self);
|
||||
|
||||
int i := 0;
|
||||
int j := 0;
|
||||
int d := -1;
|
||||
int start := 0;
|
||||
int end := self*self - 1;
|
||||
|
||||
while (start < end)
|
||||
{
|
||||
result.setAt(i, j, start); start += 1;
|
||||
result.setAt(self - i - 1, self - j - 1, end); end -= 1;
|
||||
|
||||
i := i + d;
|
||||
j := j - d;
|
||||
if (i < 0)
|
||||
{
|
||||
i:=i+1; d := d.Negative
|
||||
}
|
||||
else if (j < 0)
|
||||
{
|
||||
j := j + 1; d := d.Negative
|
||||
}
|
||||
};
|
||||
|
||||
if (start == end)
|
||||
{
|
||||
result.setAt(i, j, start)
|
||||
};
|
||||
|
||||
^ result
|
||||
}
|
||||
}
|
||||
|
||||
public program()
|
||||
{
|
||||
console.printLine(5.zigzagMatrix()).readChar()
|
||||
}
|
||||
15
Task/Zig-zag-matrix/Elixir/zig-zag-matrix.elixir
Normal file
15
Task/Zig-zag-matrix/Elixir/zig-zag-matrix.elixir
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
defmodule RC do
|
||||
require Integer
|
||||
def zigzag(n) do
|
||||
fmt = "~#{to_char_list(n*n-1) |> length}w "
|
||||
(for x <- 1..n, y <- 1..n, do: {x,y})
|
||||
|> Enum.sort_by(fn{x,y}->{x+y, if(Integer.is_even(x+y), do: y, else: x)} end)
|
||||
|> Enum.with_index |> Enum.sort
|
||||
|> Enum.each(fn {{_x,y},i} ->
|
||||
:io.format fmt, [i]
|
||||
if y==n, do: IO.puts ""
|
||||
end)
|
||||
end
|
||||
end
|
||||
|
||||
RC.zigzag(5)
|
||||
28
Task/Zig-zag-matrix/Erlang/zig-zag-matrix.erl
Normal file
28
Task/Zig-zag-matrix/Erlang/zig-zag-matrix.erl
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
-module( zigzag ).
|
||||
|
||||
-export( [matrix/1, task/0] ).
|
||||
|
||||
matrix( N ) ->
|
||||
{{_X_Y, N}, Proplist} = lists:foldl( fun matrix_as_proplist/2, {{{0, 0}, N}, []}, lists:seq(0, (N * N) - 1) ),
|
||||
[columns( X, Proplist ) || X <- lists:seq(0, N - 1)].
|
||||
|
||||
task() -> matrix( 5 ).
|
||||
|
||||
|
||||
|
||||
columns( Column, Proplist ) -> lists:sort( [Value || {{_X, Y}, Value} <- Proplist, Y =:= Column] ).
|
||||
|
||||
matrix_as_proplist( N, {{X_Y, Max}, Acc} ) ->
|
||||
Next = next_indexes( X_Y, Max ),
|
||||
{{Next, Max}, [{X_Y, N} | Acc]}.
|
||||
|
||||
next_indexes( {X, Y}, Max ) when Y + 1 =:= Max, (X + Y) rem 2 =:= 0 -> {X + 1, Y - 1};
|
||||
next_indexes( {X, Y}, Max ) when Y + 1 =:= Max, (X + Y) rem 2 =:= 1 -> {X + 1, Y};
|
||||
next_indexes( {X, Y}, Max ) when X + 1 =:= Max, (X + Y) rem 2 =:= 0 -> {X, Y + 1};
|
||||
next_indexes( {X, Y}, Max ) when X + 1 =:= Max, (X + Y) rem 2 =:= 1 -> {X - 1, Y + 1};
|
||||
next_indexes( {X, 0}, _Max ) when X rem 2 =:= 0 -> {X + 1, 0};
|
||||
next_indexes( {X, 0}, _Max ) when X rem 2 =:= 1 -> {X - 1, 1};
|
||||
next_indexes( {0, Y}, _Max ) when Y rem 2 =:= 0 -> {1, Y - 1};
|
||||
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}.
|
||||
20
Task/Zig-zag-matrix/Euphoria/zig-zag-matrix.euphoria
Normal file
20
Task/Zig-zag-matrix/Euphoria/zig-zag-matrix.euphoria
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
function zigzag(integer size)
|
||||
sequence s
|
||||
integer i, j, d, max
|
||||
s = repeat(repeat(0,size),size)
|
||||
i = 1 j = 1 d = -1
|
||||
max = size*size
|
||||
for n = 1 to floor(max/2)+1 do
|
||||
s[i][j] = n
|
||||
s[size-i+1][size-j+1] = max-n+1
|
||||
i += d j-= d
|
||||
if i < 1 then
|
||||
i += 1 d = -d
|
||||
elsif j < 1 then
|
||||
j += 1 d = -d
|
||||
end if
|
||||
end for
|
||||
return s
|
||||
end function
|
||||
|
||||
? zigzag(5)
|
||||
14
Task/Zig-zag-matrix/F-Sharp/zig-zag-matrix-1.fs
Normal file
14
Task/Zig-zag-matrix/F-Sharp/zig-zag-matrix-1.fs
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
//Produce a zig zag matrix - Nigel Galloway: April 7th., 2015
|
||||
let zz l a =
|
||||
let N = Array2D.create l a 0
|
||||
let rec gng (n, i, g, e) =
|
||||
N.[n,i] <- g
|
||||
match e with
|
||||
| _ when i=a-1 && n=l-1 -> N
|
||||
| 1 when n = l-1 -> gng (n, i+1, g+1, 2)
|
||||
| 2 when i = a-1 -> gng (n+1, i, g+1, 1)
|
||||
| 1 when i = 0 -> gng (n+1, 0, g+1, 2)
|
||||
| 2 when n = 0 -> gng (0, i+1, g+1, 1)
|
||||
| 1 -> gng (n+1, i-1, g+1, 1)
|
||||
| _ -> gng (n-1, i+1, g+1, 2)
|
||||
gng (0, 0, 0, 2)
|
||||
1
Task/Zig-zag-matrix/F-Sharp/zig-zag-matrix-2.fs
Normal file
1
Task/Zig-zag-matrix/F-Sharp/zig-zag-matrix-2.fs
Normal file
|
|
@ -0,0 +1 @@
|
|||
zz 5 5
|
||||
1
Task/Zig-zag-matrix/F-Sharp/zig-zag-matrix-3.fs
Normal file
1
Task/Zig-zag-matrix/F-Sharp/zig-zag-matrix-3.fs
Normal file
|
|
@ -0,0 +1 @@
|
|||
zz 8 8
|
||||
1
Task/Zig-zag-matrix/F-Sharp/zig-zag-matrix-4.fs
Normal file
1
Task/Zig-zag-matrix/F-Sharp/zig-zag-matrix-4.fs
Normal file
|
|
@ -0,0 +1 @@
|
|||
zz 5 8
|
||||
25
Task/Zig-zag-matrix/Factor/zig-zag-matrix-1.factor
Normal file
25
Task/Zig-zag-matrix/Factor/zig-zag-matrix-1.factor
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
USING: columns fry kernel make math math.ranges prettyprint
|
||||
sequences sequences.cords sequences.extras ;
|
||||
IN: rosetta-code.zig-zag-matrix
|
||||
|
||||
: [1,b,1] ( n -- seq )
|
||||
[1,b] dup but-last-slice <reversed> cord-append ;
|
||||
|
||||
: <reversed-evens> ( seq -- seq' )
|
||||
[ even? [ <reversed> ] when ] map-index ;
|
||||
|
||||
: diagonals ( n -- seq )
|
||||
[ sq <iota> ] [ [1,b,1] ] bi
|
||||
[ [ cut [ , ] dip ] each ] { } make nip <reversed-evens> ;
|
||||
|
||||
: zig-zag-matrix ( n -- seq )
|
||||
[ diagonals ] [ dup ] bi '[
|
||||
[
|
||||
dup 0 <column> _ head ,
|
||||
[ _ < [ rest-slice ] when ] map-index harvest
|
||||
] until-empty
|
||||
] { } make ;
|
||||
|
||||
: zig-zag-demo ( -- ) 5 zig-zag-matrix simple-table. ;
|
||||
|
||||
MAIN: zig-zag-demo
|
||||
11
Task/Zig-zag-matrix/Factor/zig-zag-matrix-2.factor
Normal file
11
Task/Zig-zag-matrix/Factor/zig-zag-matrix-2.factor
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
USING: assocs assocs.extras grouping io kernel math
|
||||
math.combinatorics math.matrices prettyprint sequences ;
|
||||
|
||||
: <zig-zag-matrix> ( n -- matrix )
|
||||
[
|
||||
dup [ + ] <matrix-by-indices> concat zip-index
|
||||
expand-keys-push-at values [ even? [ reverse ] when ]
|
||||
map-index concat inverse-permutation
|
||||
] [ group ] bi ;
|
||||
|
||||
5 <zig-zag-matrix> simple-table.
|
||||
91
Task/Zig-zag-matrix/Fan/zig-zag-matrix.fan
Normal file
91
Task/Zig-zag-matrix/Fan/zig-zag-matrix.fan
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
using gfx // for Point; convenient x/y wrapper
|
||||
|
||||
**
|
||||
** A couple methods for generating a 'zigzag' array like
|
||||
**
|
||||
** 0 1 5 6
|
||||
** 2 4 7 12
|
||||
** 3 8 11 13
|
||||
** 9 10 14 15
|
||||
**
|
||||
class ZigZag
|
||||
{
|
||||
** return an n x n array of uninitialized Int
|
||||
static Int[][] makeSquareArray(Int n)
|
||||
{
|
||||
Int[][] grid := Int[][,] {it.size=n}
|
||||
n.times |i| { grid[i] = Int[,] {it.size=n} }
|
||||
return grid
|
||||
}
|
||||
|
||||
|
||||
Int[][] zig(Int n)
|
||||
{
|
||||
grid := makeSquareArray(n)
|
||||
|
||||
move := |Int i, Int j->Point|
|
||||
{ return j < n - 1 ? Point(i <= 0 ? 0 : i-1, j+1) : Point(i+1, j) }
|
||||
pt := Point(0,0)
|
||||
(n*n).times |i| {
|
||||
grid[pt.y][pt.x] = i
|
||||
if ((pt.x+pt.y)%2 != 0) pt = move(pt.x,pt.y)
|
||||
else {tmp:= move(pt.y,pt.x); pt = Point(tmp.y, tmp.x) }
|
||||
}
|
||||
return grid
|
||||
}
|
||||
|
||||
public static Int[][] zag(Int size)
|
||||
{
|
||||
data := makeSquareArray(size)
|
||||
|
||||
Int i := 1
|
||||
Int j := 1
|
||||
for (element:=0; element < size * size; element++)
|
||||
{
|
||||
data[i - 1][j - 1] = element
|
||||
if((i + j) % 2 == 0) {
|
||||
// Even stripes
|
||||
if (j < size) {
|
||||
j++
|
||||
} else {
|
||||
i += 2
|
||||
}
|
||||
if (i > 1) {
|
||||
i--
|
||||
}
|
||||
} else {
|
||||
// Odd stripes
|
||||
if (i < size) {
|
||||
i++;
|
||||
} else {
|
||||
j += 2
|
||||
}
|
||||
if (j > 1) {
|
||||
j--
|
||||
}
|
||||
}
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
Void print(Int[][] data)
|
||||
{
|
||||
data.each |row|
|
||||
{
|
||||
buf := StrBuf()
|
||||
row.each |num|
|
||||
{
|
||||
buf.add(num.toStr.justr(3))
|
||||
}
|
||||
echo(buf)
|
||||
}
|
||||
}
|
||||
|
||||
Void main()
|
||||
{
|
||||
echo("zig method:")
|
||||
print(zig(8))
|
||||
echo("\nzag method:")
|
||||
print(zag(8))
|
||||
}
|
||||
}
|
||||
50
Task/Zig-zag-matrix/Forth/zig-zag-matrix.fth
Normal file
50
Task/Zig-zag-matrix/Forth/zig-zag-matrix.fth
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
0 value diag
|
||||
|
||||
: south diag abs + cell+ ;
|
||||
|
||||
' cell+ value zig
|
||||
' south value zag
|
||||
|
||||
: init ( n -- )
|
||||
1- cells negate to diag
|
||||
['] cell+ to zig
|
||||
['] south to zag ;
|
||||
|
||||
: swap-diag zig zag to zig to zag ;
|
||||
|
||||
: put ( n addr -- n+1 addr )
|
||||
2dup ! swap 1+ swap ;
|
||||
|
||||
: turn ( addr -- addr+E/S )
|
||||
zig execute swap-diag
|
||||
diag negate to diag ;
|
||||
|
||||
: zigzag ( matrix n -- )
|
||||
{ n } n init
|
||||
0 swap
|
||||
n 1 ?do
|
||||
put turn
|
||||
i 0 do put diag + loop
|
||||
loop
|
||||
swap-diag
|
||||
n 1 ?do
|
||||
put turn
|
||||
n i 1+ ?do put diag + loop
|
||||
loop
|
||||
! ;
|
||||
|
||||
: .matrix ( n matrix -- )
|
||||
over 0 do
|
||||
cr
|
||||
over 0 do
|
||||
dup @ 3 .r cell+
|
||||
loop
|
||||
loop 2drop ;
|
||||
|
||||
: test ( n -- ) here over zigzag here .matrix ;
|
||||
5 test
|
||||
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 ok
|
||||
38
Task/Zig-zag-matrix/Fortran/zig-zag-matrix.f
Normal file
38
Task/Zig-zag-matrix/Fortran/zig-zag-matrix.f
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
PROGRAM ZIGZAG
|
||||
|
||||
IMPLICIT NONE
|
||||
INTEGER, PARAMETER :: size = 5
|
||||
INTEGER :: zzarray(size,size), x(size*size), y(size*size), i, j
|
||||
|
||||
! index arrays
|
||||
x = (/ ((j, i = 1, size), j = 1, size) /)
|
||||
y = (/ ((i, i = 1, size), j = 1, size) /)
|
||||
|
||||
! Sort indices
|
||||
DO i = 2, size*size
|
||||
j = i - 1
|
||||
DO WHILE (j>=1 .AND. (x(j)+y(j)) > (x(i)+y(i)))
|
||||
j = j - 1
|
||||
END DO
|
||||
x(j+1:i) = cshift(x(j+1:i),-1)
|
||||
y(j+1:i) = cshift(y(j+1:i),-1)
|
||||
END DO
|
||||
|
||||
! Create zig zag array
|
||||
DO i = 1, size*size
|
||||
IF (MOD(x(i)+y(i), 2) == 0) THEN
|
||||
zzarray(x(i),y(i)) = i - 1
|
||||
ELSE
|
||||
zzarray(y(i),x(i)) = i - 1
|
||||
END IF
|
||||
END DO
|
||||
|
||||
! Print zig zag array
|
||||
DO j = 1, size
|
||||
DO i = 1, size
|
||||
WRITE(*, "(I5)", ADVANCE="NO") zzarray(i,j)
|
||||
END DO
|
||||
WRITE(*,*)
|
||||
END DO
|
||||
|
||||
END PROGRAM ZIGZAG
|
||||
74
Task/Zig-zag-matrix/FreeBASIC/zig-zag-matrix.basic
Normal file
74
Task/Zig-zag-matrix/FreeBASIC/zig-zag-matrix.basic
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
' FB 1.05.0 Win64
|
||||
|
||||
Dim As Integer n
|
||||
|
||||
Do
|
||||
Input "Enter size of matrix "; n
|
||||
Loop Until n > 0
|
||||
|
||||
Dim zigzag(1 To n, 1 To n) As Integer '' all zero by default
|
||||
|
||||
' enter the numbers 0 to (n^2 - 1) in the matrix's anti-diagonals
|
||||
zigzag(1, 1) = 0
|
||||
If n > 1 Then
|
||||
Dim As Integer row = 0, col = 3
|
||||
Dim As Boolean down = true, increment = true
|
||||
Dim As Integer i = 0, j = 2, k
|
||||
Do
|
||||
If down Then
|
||||
For k = 1 To j
|
||||
i += 1
|
||||
row += 1
|
||||
col -= 1
|
||||
zigzag(row, col) = i
|
||||
Next
|
||||
down = false
|
||||
Else
|
||||
For k = 1 To j
|
||||
i += 1
|
||||
row -= 1
|
||||
col += 1
|
||||
zigzag(row, col) = i
|
||||
Next
|
||||
down = true
|
||||
End If
|
||||
If increment Then
|
||||
j += 1
|
||||
If j > n Then
|
||||
j = n - 1
|
||||
increment = false
|
||||
End If
|
||||
Else
|
||||
j -= 1
|
||||
If j = 0 Then Exit Do
|
||||
End If
|
||||
If down AndAlso increment Then
|
||||
col += 2
|
||||
row -= 1
|
||||
ElseIf Not Down AndAlso increment Then
|
||||
row += 2
|
||||
col -= 1
|
||||
ElseIf down AndAlso Not increment Then
|
||||
col += 1
|
||||
Else '' Not down AndAlso NotIncrement
|
||||
row += 1
|
||||
End If
|
||||
Loop
|
||||
End If
|
||||
|
||||
' print zigzag 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 "####"; zigzag(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
|
||||
36
Task/Zig-zag-matrix/GAP/zig-zag-matrix.gap
Normal file
36
Task/Zig-zag-matrix/GAP/zig-zag-matrix.gap
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
ZigZag := function(n)
|
||||
local a, i, j, k;
|
||||
a := NullMat(n, n);
|
||||
i := 1;
|
||||
j := 1;
|
||||
for k in [0 .. n*n - 1] do
|
||||
a[i][j] := k;
|
||||
if (i + j) mod 2 = 0 then
|
||||
if j < n then
|
||||
j := j + 1;
|
||||
else
|
||||
i := i + 2;
|
||||
fi;
|
||||
if i > 1 then
|
||||
i := i - 1;
|
||||
fi;
|
||||
else
|
||||
if i < n then
|
||||
i := i + 1;
|
||||
else
|
||||
j := j + 2;
|
||||
fi;
|
||||
if j > 1 then
|
||||
j := j - 1;
|
||||
fi;
|
||||
fi;
|
||||
od;
|
||||
return a;
|
||||
end;
|
||||
|
||||
PrintArray(ZigZag(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 ] ]
|
||||
47
Task/Zig-zag-matrix/Go/zig-zag-matrix.go
Normal file
47
Task/Zig-zag-matrix/Go/zig-zag-matrix.go
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func zz(n int) []int {
|
||||
r := make([]int, n*n)
|
||||
i := 0
|
||||
n2 := n * 2
|
||||
for d := 1; d <= n2; d++ {
|
||||
x := d - n
|
||||
if x < 0 {
|
||||
x = 0
|
||||
}
|
||||
y := d - 1
|
||||
if y > n-1 {
|
||||
y = n - 1
|
||||
}
|
||||
j := n2 - d
|
||||
if j > d {
|
||||
j = d
|
||||
}
|
||||
for k := 0; k < j; k++ {
|
||||
if d&1 == 0 {
|
||||
r[(x+k)*n+y-k] = i
|
||||
} else {
|
||||
r[(y-k)*n+x+k] = i
|
||||
}
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
func main() {
|
||||
const n = 5
|
||||
w := len(strconv.Itoa(n*n - 1))
|
||||
for i, e := range zz(n) {
|
||||
fmt.Printf("%*d ", w, e)
|
||||
if i%n == n-1 {
|
||||
fmt.Println("")
|
||||
}
|
||||
}
|
||||
}
|
||||
11
Task/Zig-zag-matrix/Groovy/zig-zag-matrix-1.groovy
Normal file
11
Task/Zig-zag-matrix/Groovy/zig-zag-matrix-1.groovy
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
def zz = { n ->
|
||||
grid = new int[n][n]
|
||||
i = 0
|
||||
for (d in 1..n*2) {
|
||||
(x, y) = [Math.max(0, d - n), Math.min(n - 1, d - 1)]
|
||||
Math.min(d, n*2 - d).times {
|
||||
grid[d%2?y-it:x+it][d%2?x+it:y-it] = i++;
|
||||
}
|
||||
}
|
||||
grid
|
||||
}
|
||||
11
Task/Zig-zag-matrix/Groovy/zig-zag-matrix-2.groovy
Normal file
11
Task/Zig-zag-matrix/Groovy/zig-zag-matrix-2.groovy
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
def zz = { n->
|
||||
move = { i, j -> j < n - 1 ? [i <= 0 ? 0 : i-1, j+1] : [i+1, j] }
|
||||
grid = new int[n][n]
|
||||
(x, y) = [0, 0]
|
||||
(n**2).times {
|
||||
grid[y][x] = it
|
||||
if ((x+y)%2) (x,y) = move(x,y)
|
||||
else (y,x) = move(y,x)
|
||||
}
|
||||
grid
|
||||
}
|
||||
5
Task/Zig-zag-matrix/Groovy/zig-zag-matrix-3.groovy
Normal file
5
Task/Zig-zag-matrix/Groovy/zig-zag-matrix-3.groovy
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
def zz = { n ->
|
||||
(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 } }
|
||||
}
|
||||
15
Task/Zig-zag-matrix/Haskell/zig-zag-matrix-1.hs
Normal file
15
Task/Zig-zag-matrix/Haskell/zig-zag-matrix-1.hs
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import Data.Array (Array, array, bounds, range, (!))
|
||||
import Text.Printf (printf)
|
||||
import Data.List (sortBy)
|
||||
|
||||
compZig :: (Int, Int) -> (Int, Int) -> Ordering
|
||||
compZig (x, y) (x_, y_) = compare (x + y) (x_ + y_) <> go x y
|
||||
where
|
||||
go x y
|
||||
| even (x + y) = compare x x_
|
||||
| otherwise = compare y y_
|
||||
|
||||
zigZag :: (Int, Int) -> Array (Int, Int) Int
|
||||
zigZag upper = array b $ zip (sortBy compZig (range b)) [0 ..]
|
||||
where
|
||||
b = ((0, 0), upper)
|
||||
12
Task/Zig-zag-matrix/Haskell/zig-zag-matrix-2.hs
Normal file
12
Task/Zig-zag-matrix/Haskell/zig-zag-matrix-2.hs
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
-- format a 2d array of integers neatly
|
||||
show2d a =
|
||||
unlines
|
||||
[ unwords
|
||||
[ printf "%3d" (a ! (x, y) :: Integer)
|
||||
| x <- axis fst ]
|
||||
| y <- axis snd ]
|
||||
where
|
||||
(l, h) = bounds a
|
||||
axis f = [f l .. f h]
|
||||
|
||||
main = mapM_ (putStr . ('\n' :) . show2d . zigZag) [(3, 3), (4, 4), (10, 2)]
|
||||
26
Task/Zig-zag-matrix/Haskell/zig-zag-matrix-3.hs
Normal file
26
Task/Zig-zag-matrix/Haskell/zig-zag-matrix-3.hs
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
import Data.Text (justifyRight, pack, unpack)
|
||||
import Data.List (mapAccumL)
|
||||
import Data.Bool (bool)
|
||||
|
||||
zigZag :: Int -> [[Int]]
|
||||
zigZag = go <*> diagonals
|
||||
where
|
||||
go _ [] = []
|
||||
go n xss = (head <$> edge) : go n (dropWhile null (tail <$> edge) <> rst)
|
||||
where
|
||||
(edge, rst) = splitAt n xss
|
||||
|
||||
diagonals :: Int -> [[Int]]
|
||||
diagonals n =
|
||||
snd $ mapAccumL go [0 .. (n * n) - 1] (slope <> [n] <> reverse slope)
|
||||
where
|
||||
slope = [1 .. n - 1]
|
||||
go xs h = (rst, bool id reverse (0 /= mod h 2) grp)
|
||||
where
|
||||
(grp, rst) = splitAt h xs
|
||||
|
||||
main :: IO ()
|
||||
main =
|
||||
putStrLn $
|
||||
unlines $
|
||||
concatMap unpack . fmap (justifyRight 3 ' ' . pack . show) <$> zigZag 5
|
||||
28
Task/Zig-zag-matrix/IS-BASIC/zig-zag-matrix.basic
Normal file
28
Task/Zig-zag-matrix/IS-BASIC/zig-zag-matrix.basic
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
100 PROGRAM "ZigZag.bas"
|
||||
110 LET SIZE=5
|
||||
120 NUMERIC A(1 TO SIZE,1 TO SIZE)
|
||||
130 LET I,J=1
|
||||
140 FOR E=0 TO SIZE^2-1
|
||||
150 LET A(I,J)=E
|
||||
160 IF ((I+J) BAND 1)=0 THEN
|
||||
170 IF J<SIZE THEN
|
||||
180 LET J=J+1
|
||||
190 ELSE
|
||||
200 LET I=I+2
|
||||
210 END IF
|
||||
220 IF I>1 THEN LET I=I-1
|
||||
230 ELSE
|
||||
240 IF I<SIZE THEN
|
||||
250 LET I=I+1
|
||||
260 ELSE
|
||||
270 LET J=J+2
|
||||
280 END IF
|
||||
290 IF J>1 THEN LET J=J-1
|
||||
300 END IF
|
||||
310 NEXT
|
||||
320 FOR ROW=1 TO SIZE
|
||||
330 FOR COL=1 TO SIZE
|
||||
340 PRINT USING " ##":A(ROW,COL);
|
||||
350 NEXT
|
||||
360 PRINT
|
||||
370 NEXT
|
||||
25
Task/Zig-zag-matrix/Icon/zig-zag-matrix.icon
Normal file
25
Task/Zig-zag-matrix/Icon/zig-zag-matrix.icon
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
procedure main(args)
|
||||
n := integer(!args) | 5
|
||||
every !(A := list(n)) := list(n)
|
||||
A := zigzag(A)
|
||||
show(A)
|
||||
end
|
||||
|
||||
procedure show(A)
|
||||
every writes(right(!A,5) | "\n")
|
||||
end
|
||||
|
||||
procedure zigzag(A)
|
||||
x := [0,0]
|
||||
every i := 0 to (*A^2 -1) do {
|
||||
x := nextIndices(*A, x)
|
||||
A[x[1]][x[2]] := i
|
||||
}
|
||||
return A
|
||||
end
|
||||
|
||||
procedure nextIndices(n, x)
|
||||
return if (x[1]+x[2])%2 = 0
|
||||
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
|
||||
6
Task/Zig-zag-matrix/J/zig-zag-matrix-1.j
Normal file
6
Task/Zig-zag-matrix/J/zig-zag-matrix-1.j
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
($ [: /:@; <@|.`</.@i.)@,~ 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
|
||||
6
Task/Zig-zag-matrix/J/zig-zag-matrix-2.j
Normal file
6
Task/Zig-zag-matrix/J/zig-zag-matrix-2.j
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
($ [: /:@; [: <@(A.~_2|#)/. i.)@,~ 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
|
||||
6
Task/Zig-zag-matrix/J/zig-zag-matrix-3.j
Normal file
6
Task/Zig-zag-matrix/J/zig-zag-matrix-3.j
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
($ ([: /:@;@(+/"1 <@|.`</. ]) (#: i.@(*/))))@,~ 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
|
||||
6
Task/Zig-zag-matrix/J/zig-zag-matrix-4.j
Normal file
6
Task/Zig-zag-matrix/J/zig-zag-matrix-4.j
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
($ [: /:@; [: <@|.`</. i.) 5 3
|
||||
0 1 5
|
||||
2 4 6
|
||||
3 7 11
|
||||
8 10 12
|
||||
9 13 14
|
||||
31
Task/Zig-zag-matrix/Java/zig-zag-matrix.java
Normal file
31
Task/Zig-zag-matrix/Java/zig-zag-matrix.java
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
public static int[][] Zig_Zag(final int size)
|
||||
{
|
||||
int[][] data = new int[size][size];
|
||||
int i = 1;
|
||||
int j = 1;
|
||||
for (int element = 0; element < size * size; element++)
|
||||
{
|
||||
data[i - 1][j - 1] = element;
|
||||
if ((i + j) % 2 == 0)
|
||||
{
|
||||
// Even stripes
|
||||
if (j < size)
|
||||
j++;
|
||||
else
|
||||
i+= 2;
|
||||
if (i > 1)
|
||||
i--;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Odd stripes
|
||||
if (i < size)
|
||||
i++;
|
||||
else
|
||||
j+= 2;
|
||||
if (j > 1)
|
||||
j--;
|
||||
}
|
||||
}
|
||||
return data;
|
||||
}
|
||||
32
Task/Zig-zag-matrix/JavaScript/zig-zag-matrix-1.js
Normal file
32
Task/Zig-zag-matrix/JavaScript/zig-zag-matrix-1.js
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
function ZigZagMatrix(n) {
|
||||
this.height = n;
|
||||
this.width = n;
|
||||
|
||||
this.mtx = [];
|
||||
for (var i = 0; i < n; i++)
|
||||
this.mtx[i] = [];
|
||||
|
||||
var i=1, j=1;
|
||||
for (var e = 0; e < n*n; e++) {
|
||||
this.mtx[i-1][j-1] = e;
|
||||
if ((i + j) % 2 == 0) {
|
||||
// Even stripes
|
||||
if (j < n) j ++;
|
||||
else i += 2;
|
||||
if (i > 1) i --;
|
||||
} else {
|
||||
// Odd stripes
|
||||
if (i < n) i ++;
|
||||
else j += 2;
|
||||
if (j > 1) j --;
|
||||
}
|
||||
}
|
||||
}
|
||||
ZigZagMatrix.prototype = Matrix.prototype;
|
||||
|
||||
var z = new ZigZagMatrix(5);
|
||||
print(z);
|
||||
print();
|
||||
|
||||
z = new ZigZagMatrix(4);
|
||||
print(z);
|
||||
97
Task/Zig-zag-matrix/JavaScript/zig-zag-matrix-2.js
Normal file
97
Task/Zig-zag-matrix/JavaScript/zig-zag-matrix-2.js
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
(function (n) {
|
||||
|
||||
// Read range of values into a series of 'diagonal rows'
|
||||
// for a square of given dimension,
|
||||
// starting at diagonal row i.
|
||||
// [
|
||||
// [0],
|
||||
// [1, 2],
|
||||
// [3, 4, 5],
|
||||
// [6, 7, 8, 9],
|
||||
// [10, 11, 12, 13, 14],
|
||||
// [15, 16, 17, 18],
|
||||
// [19, 20, 21],
|
||||
// [22, 23],
|
||||
// [24]
|
||||
// ]
|
||||
|
||||
// diagonals :: n -> [[n]]
|
||||
function diagonals(n) {
|
||||
function diags(xs, iCol, iRow) {
|
||||
if (iCol < xs.length) {
|
||||
var xxs = splitAt(iCol, xs);
|
||||
|
||||
return [xxs[0]].concat(diags(
|
||||
xxs[1],
|
||||
(iCol + (iRow < n ? 1 : -1)),
|
||||
iRow + 1
|
||||
));
|
||||
} else return [xs];
|
||||
}
|
||||
|
||||
return diags(range(0, n * n - 1), 1, 1);
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Recursively read off n heads from the diagonals (as rows)
|
||||
// n -> [[n]] -> [[n]]
|
||||
function nHeads(n, lst) {
|
||||
var zipEdge = lst.slice(0, n);
|
||||
|
||||
return lst.length ? [zipEdge.map(function (x) {
|
||||
return x[0];
|
||||
})].concat(nHeads(n, [].concat.apply([], zipEdge.map(function (
|
||||
x) {
|
||||
return x.length > 1 ? [x.slice(1)] : [];
|
||||
}))
|
||||
.concat(lst.slice(n)))) : [];
|
||||
}
|
||||
|
||||
// range(intFrom, intTo, optional intStep)
|
||||
// Int -> Int -> Maybe Int -> [Int]
|
||||
function range(m, n, delta) {
|
||||
var d = delta || 1,
|
||||
blnUp = n > m,
|
||||
lng = Math.floor((blnUp ? n - m : m - n) / d) + 1,
|
||||
a = Array(lng),
|
||||
i = lng;
|
||||
|
||||
if (blnUp)
|
||||
while (i--) a[i] = (d * i) + m;
|
||||
else
|
||||
while (i--) a[i] = m - (d * i);
|
||||
return a;
|
||||
}
|
||||
|
||||
// splitAt :: Int -> [a] -> ([a],[a])
|
||||
function splitAt(n, xs) {
|
||||
return [xs.slice(0, n), xs.slice(n)];
|
||||
}
|
||||
|
||||
// Recursively take n heads from the alternately reversed diagonals
|
||||
|
||||
// [ [
|
||||
// [0], -> [0, 1, 5, 6, 14] and:
|
||||
// [1, 2], [2],
|
||||
// [5, 4, 3], [4, 3],
|
||||
// [6, 7, 8, 9], [7, 8, 9],
|
||||
// [14, 13, 12, 11, 10], [13, 12, 11, 10],
|
||||
// [15, 16, 17, 18], [15, 16, 17, 18],
|
||||
// [21, 20, 19], [21, 20, 19],
|
||||
// [22, 23], [22, 23],
|
||||
// [24] [24]
|
||||
// ] ]
|
||||
//
|
||||
// In the next recursion with the remnant on the right, the next
|
||||
// 5 heads will be [2, 4, 7, 13, 15] - the second row of our zig zag matrix.
|
||||
// (and so forth)
|
||||
|
||||
|
||||
return nHeads(n, diagonals(n)
|
||||
.map(function (x, i) {
|
||||
i % 2 || x.reverse();
|
||||
return x;
|
||||
}));
|
||||
|
||||
})(5);
|
||||
60
Task/Zig-zag-matrix/JavaScript/zig-zag-matrix-3.js
Normal file
60
Task/Zig-zag-matrix/JavaScript/zig-zag-matrix-3.js
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
(n => {
|
||||
|
||||
// diagonals :: n -> [[n]]
|
||||
function diagonals(n) {
|
||||
let diags = (xs, iCol, iRow) => {
|
||||
if (iCol < xs.length) {
|
||||
let xxs = splitAt(iCol, xs);
|
||||
|
||||
return [xxs[0]].concat(diags(
|
||||
xxs[1],
|
||||
iCol + (iRow < n ? 1 : -1),
|
||||
iRow + 1
|
||||
));
|
||||
} else return [xs];
|
||||
}
|
||||
|
||||
return diags(range(0, n * n - 1), 1, 1);
|
||||
}
|
||||
|
||||
|
||||
// Recursively read off n heads of diagonal lists
|
||||
// rowsFromDiagonals :: n -> [[n]] -> [[n]]
|
||||
function rowsFromDiagonals(n, lst) {
|
||||
if (lst.length) {
|
||||
let [edge, rest] = splitAt(n, lst);
|
||||
|
||||
return [edge.map(x => x[0])]
|
||||
.concat(rowsFromDiagonals(n,
|
||||
edge.filter(x => x.length > 1)
|
||||
.map(x => x.slice(1))
|
||||
.concat(rest)
|
||||
));
|
||||
} else return [];
|
||||
}
|
||||
|
||||
// GENERIC FUNCTIONS
|
||||
|
||||
// splitAt :: Int -> [a] -> ([a],[a])
|
||||
function splitAt(n, xs) {
|
||||
return [xs.slice(0, n), xs.slice(n)];
|
||||
}
|
||||
|
||||
// range :: From -> To -> Maybe Step -> [Int]
|
||||
// range :: Int -> Int -> Maybe Int -> [Int]
|
||||
function range(m, n, step) {
|
||||
let d = (step || 1) * (n >= m ? 1 : -1);
|
||||
|
||||
return Array.from({
|
||||
length: Math.floor((n - m) / d) + 1
|
||||
}, (_, i) => m + (i * d));
|
||||
}
|
||||
|
||||
// ZIG-ZAG MATRIX
|
||||
|
||||
return rowsFromDiagonals(n,
|
||||
diagonals(n)
|
||||
.map((x, i) => (i % 2 || x.reverse()) && x)
|
||||
);
|
||||
|
||||
})(5);
|
||||
51
Task/Zig-zag-matrix/Joy/zig-zag-matrix.joy
Normal file
51
Task/Zig-zag-matrix/Joy/zig-zag-matrix.joy
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
(*
|
||||
From the library.
|
||||
*)
|
||||
DEFINE reverse == [] swap shunt;
|
||||
shunt == [swons] step.
|
||||
|
||||
(*
|
||||
Split according to the parameter given.
|
||||
*)
|
||||
DEFINE take-drop == [dup] swap dup [[] cons [take swap] concat concat] dip []
|
||||
cons concat [drop] concat.
|
||||
|
||||
(*
|
||||
Take the first of a list of lists.
|
||||
*)
|
||||
DEFINE take-first == [] cons 3 [dup] times [dup] swap concat [take [first] map
|
||||
swap dup] concat swap concat [drop swap] concat swap
|
||||
concat [take [rest] step []] concat swap concat [[cons]
|
||||
times swap concat 1 drop] concat.
|
||||
|
||||
DEFINE zigzag ==
|
||||
|
||||
(*
|
||||
Use take-drop to generate a list of lists.
|
||||
*)
|
||||
4 [dup] times 1 swap from-to-list swap pred 1 swap from-to-list reverse concat
|
||||
swap dup * pred 0 swap from-to-list swap [take-drop i] step [pop list] [cons]
|
||||
while
|
||||
|
||||
(*
|
||||
The odd numbers must be modified with reverse.
|
||||
*)
|
||||
[dup size 2 div popd [1 =] [pop reverse] [pop] ifte] map
|
||||
|
||||
(*
|
||||
Take the first of the first of n lists.
|
||||
*)
|
||||
swap dup take-first [i] cons times pop
|
||||
|
||||
(*
|
||||
Merge the n separate lists.
|
||||
*)
|
||||
[] [pop list] [cons] while
|
||||
|
||||
(*
|
||||
And print them.
|
||||
*)
|
||||
swap dup * pred 'd 1 1 format size succ [] cons 'd swons [1 format putchars]
|
||||
concat [step '\n putch] cons step.
|
||||
|
||||
11 zigzag.
|
||||
18
Task/Zig-zag-matrix/Jq/zig-zag-matrix-1.jq
Normal file
18
Task/Zig-zag-matrix/Jq/zig-zag-matrix-1.jq
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
# 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" ) ;
|
||||
19
Task/Zig-zag-matrix/Jq/zig-zag-matrix-2.jq
Normal file
19
Task/Zig-zag-matrix/Jq/zig-zag-matrix-2.jq
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
def zigzag(n):
|
||||
|
||||
# unless m == n*n, place m at (i,j), pointing
|
||||
# in the direction d, where d = [drow, dcolumn]:
|
||||
def _next(i; j; m; d):
|
||||
if m == (n*n) then . else .[i][j] = m end
|
||||
| if m == (n*n) - 1 then .
|
||||
elif i == n-1 then if j+1 < n then .[i][j+1] = m+1 | _next(i-1; j+2; m+2; [-1, 1]) else . end
|
||||
elif i == 0 then if j+1 < n then .[i][j+1] = m+1 | _next(i+1; j ; m+2; [ 1,-1])
|
||||
else .[i+1][j] = m+1 | _next(i+2; j-1; m+2; [ 1,-1]) end
|
||||
elif j == n-1 then if i+1 < n then .[i+1][j] = m+1 | _next(i+2; j-1; m+2; [ 1,-1]) else . end
|
||||
elif j == 0 then if i+1 < n then .[i+1][j] = m+1 | _next(i; j+1; m+2; [-1, 1])
|
||||
else .[i][j+1] = m+1 | _next(i-1; j+1; m+2; [-1, 1]) end
|
||||
else _next(i+ d[0]; j+ d[1]; m+1; d)
|
||||
end ;
|
||||
matrix(n;n;-1) | _next(0;0; 0; [0,1]) ;
|
||||
|
||||
# Example
|
||||
zigzag(5) | neatly(4)
|
||||
65
Task/Zig-zag-matrix/Jq/zig-zag-matrix-3.jq
Normal file
65
Task/Zig-zag-matrix/Jq/zig-zag-matrix-3.jq
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
#!/usr/bin/env jq -Mnrc -f
|
||||
#
|
||||
# solve zigzag matrix by constructing list of 2n+1 column "runs"
|
||||
# and then shifting them into final form.
|
||||
#
|
||||
# e.g. for n=3 initial runs are [[0],[1,2],[3,4,5],[6,7],[8]]
|
||||
# runs below are shown as columns:
|
||||
#
|
||||
# initial column runs 0 1 3 6 8
|
||||
# 2 4 7
|
||||
# 5
|
||||
#
|
||||
# reverse cols 0,2,4 0 1 5 6 8
|
||||
# 2 4 7
|
||||
# 3
|
||||
#
|
||||
# shift cols 3,4 down 0 1 5
|
||||
# 2 4 6
|
||||
# 3 7 8
|
||||
#
|
||||
# shift rows left 0 1 5
|
||||
# to get final zigzag 2 4 6
|
||||
# 3 7 8
|
||||
|
||||
def N: $n ; # size of matrix
|
||||
def NR: 2*N - 1; # number of runs
|
||||
def abs: if .<0 then -. else . end ; # absolute value
|
||||
def runlen: N-(N-.|abs) ; # length of run
|
||||
def makeruns: [
|
||||
foreach range(1;NR+1) as $r ( # for each run
|
||||
{c:0} # state counter
|
||||
; .l = ($r|runlen) # length of this run
|
||||
| .r = [range(.c;.c+.l)] # values in this run
|
||||
| .c += .l # increment counter
|
||||
; .r # produce run
|
||||
) ] ; # collect into array
|
||||
def even: .%2==0 ; # is input even?
|
||||
def reverseruns: # reverse alternate runs
|
||||
.[keys|map(select(even))[]] |= reverse ;
|
||||
def zeros: [range(.|N-length)|0] ; # array of padding zeros
|
||||
def shiftdown:
|
||||
def pad($r): # pad run with zeros
|
||||
if $r < N # determine where zeros go
|
||||
then . = . + zeros # at back for left runs
|
||||
else . = zeros + . # at front for right runs
|
||||
end ;
|
||||
reduce keys[] as $r (.;.[$r] |= pad($r)); # shift rows down with pad
|
||||
def shiftleft: [
|
||||
range(N) as $r
|
||||
| [ range($r;$r+N) as $c
|
||||
| .[$c][$r]
|
||||
]
|
||||
] ;
|
||||
def width: [.[][]]|max|tostring|1+length; # width of largest value
|
||||
def justify($w): (($w-length)*" ") + . ; # leading spaces
|
||||
def format:
|
||||
width as $w # compute width
|
||||
| map(map(tostring | justify($w)))[] # justify values
|
||||
| join(" ")
|
||||
;
|
||||
makeruns # create column runs
|
||||
| reverseruns # reverse alternate runs
|
||||
| shiftdown # shift right runs down
|
||||
| shiftleft # shift rows left
|
||||
| format # format final result
|
||||
25
Task/Zig-zag-matrix/Julia/zig-zag-matrix-1.julia
Normal file
25
Task/Zig-zag-matrix/Julia/zig-zag-matrix-1.julia
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
function zigzag_matrix(n::Int)
|
||||
matrix = zeros(Int, n, n)
|
||||
x, y = 1, 1
|
||||
for i = 0:(n*n-1)
|
||||
matrix[y,x] = i
|
||||
if (x + y) % 2 == 0
|
||||
# Even stripes
|
||||
if x < n
|
||||
x += 1
|
||||
y -= (y > 1)
|
||||
else
|
||||
y += 1
|
||||
end
|
||||
else
|
||||
# Odd stripes
|
||||
if y < n
|
||||
x -= (x > 1)
|
||||
y += 1
|
||||
else
|
||||
x += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
return matrix
|
||||
end
|
||||
59
Task/Zig-zag-matrix/Julia/zig-zag-matrix-2.julia
Normal file
59
Task/Zig-zag-matrix/Julia/zig-zag-matrix-2.julia
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
immutable ZigZag
|
||||
m::Int
|
||||
n::Int
|
||||
diag::Array{Int,1}
|
||||
cmax::Int
|
||||
numd::Int
|
||||
lohi::(Int,Int)
|
||||
end
|
||||
|
||||
function zigzag(m::Int, n::Int)
|
||||
0<m && 0<n || error("The matrix dimensions must be positive.")
|
||||
ZigZag(m, n, [-1,1], m*n, m+n-1, extrema([m,n]))
|
||||
end
|
||||
zigzag(n::Int) = zigzag(n, n)
|
||||
|
||||
type ZZState
|
||||
cnt::Int
|
||||
cell::Array{Int,1}
|
||||
dir::Int
|
||||
dnum::Int
|
||||
dlen::Int
|
||||
dcnt::Int
|
||||
end
|
||||
|
||||
Base.length(zz::ZigZag) = zz.cmax
|
||||
Base.start(zz::ZigZag) = ZZState(1, [1,1], 1, 1, 1, 1)
|
||||
Base.done(zz::ZigZag, zzs::ZZState) = zzs.cnt > zz.cmax
|
||||
|
||||
function Base.next(zz::ZigZag, zzs::ZZState)
|
||||
s = sub2ind((zz.m, zz.n), zzs.cell[1], zzs.cell[2])
|
||||
if zzs.dcnt == zzs.dlen
|
||||
if isodd(zzs.dnum)
|
||||
if zzs.cell[2] < zz.n
|
||||
zzs.cell[2] += 1
|
||||
else
|
||||
zzs.cell[1] += 1
|
||||
end
|
||||
else
|
||||
if zzs.cell[1] < zz.m
|
||||
zzs.cell[1] += 1
|
||||
else
|
||||
zzs.cell[2] += 1
|
||||
end
|
||||
end
|
||||
zzs.dcnt = 1
|
||||
zzs.dnum += 1
|
||||
zzs.dir = -zzs.dir
|
||||
if zzs.dnum <= zz.lohi[1]
|
||||
zzs.dlen += 1
|
||||
elseif zz.lohi[2] < zzs.dnum
|
||||
zzs.dlen -= 1
|
||||
end
|
||||
else
|
||||
zzs.cell += zzs.dir*zz.diag
|
||||
zzs.dcnt += 1
|
||||
end
|
||||
zzs.cnt += 1
|
||||
return (s, zzs)
|
||||
end
|
||||
24
Task/Zig-zag-matrix/Julia/zig-zag-matrix-3.julia
Normal file
24
Task/Zig-zag-matrix/Julia/zig-zag-matrix-3.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/Zig-zag-matrix/Julia/zig-zag-matrix-4.julia
Normal file
26
Task/Zig-zag-matrix/Julia/zig-zag-matrix-4.julia
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
n = 5
|
||||
println("The n = ", n, " zig-zag matrix:")
|
||||
a = zeros(Int, (n, n))
|
||||
for (i, s) in enumerate(zigzag(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(zigzag(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(zigzag(n))
|
||||
a[s] = p[i]
|
||||
end
|
||||
println(pretty(a))
|
||||
4
Task/Zig-zag-matrix/K/zig-zag-matrix.k
Normal file
4
Task/Zig-zag-matrix/K/zig-zag-matrix.k
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
f:{grid:+x#<<a,'(!#a)*- 2!a:+/!x,:x
|
||||
padded:(-#$-1+*/x)$$grid
|
||||
`0:" "/'padded}
|
||||
f 5
|
||||
31
Task/Zig-zag-matrix/Klingphix/zig-zag-matrix.klingphix
Normal file
31
Task/Zig-zag-matrix/Klingphix/zig-zag-matrix.klingphix
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
include ..\Utilitys.tlhy
|
||||
|
||||
|
||||
%Size 5 !Size
|
||||
0 ( $Size dup ) dim
|
||||
|
||||
%i 1 !i %j 1 !j
|
||||
|
||||
|
||||
$Size 2 power [
|
||||
1 -
|
||||
( $i $j ) set
|
||||
$i $j + 1 band 0 == (
|
||||
[$j $Size < ( [$j 1 + !j] [$i 2 + !i] ) if
|
||||
$i 1 > [ $i 1 - !i] if ]
|
||||
[$i $Size < ( [$i 1 + !i] [$j 2 + !j] ) if
|
||||
$j 1 > [ $j 1 - !j] if ]
|
||||
) if
|
||||
] for
|
||||
|
||||
$Size [
|
||||
%row !row
|
||||
$Size [
|
||||
%col !col
|
||||
( $row $col ) get tostr 32 32 chain chain 1 3 slice print drop
|
||||
] for
|
||||
nl
|
||||
] for
|
||||
|
||||
|
||||
nl "End " input
|
||||
37
Task/Zig-zag-matrix/Kotlin/zig-zag-matrix.kotlin
Normal file
37
Task/Zig-zag-matrix/Kotlin/zig-zag-matrix.kotlin
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
// version 1.1.3
|
||||
|
||||
typealias Vector = IntArray
|
||||
typealias Matrix = Array<Vector>
|
||||
|
||||
fun zigzagMatrix(n: Int): Matrix {
|
||||
val result = Matrix(n) { Vector(n) }
|
||||
var down = false
|
||||
var count = 0
|
||||
for (col in 0 until n) {
|
||||
if (down)
|
||||
for (row in 0..col) result[row][col - row] = count++
|
||||
else
|
||||
for (row in col downTo 0) result[row][col - row] = count++
|
||||
down = !down
|
||||
}
|
||||
for (row in 1 until n) {
|
||||
if (down)
|
||||
for (col in n - 1 downTo row) result[row + n - 1 - col][col] = count++
|
||||
else
|
||||
for (col in row until n) result[row + n - 1 - col][col] = count++
|
||||
down = !down
|
||||
}
|
||||
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(zigzagMatrix(5))
|
||||
printMatrix(zigzagMatrix(10))
|
||||
}
|
||||
32
Task/Zig-zag-matrix/Ksh/zig-zag-matrix.ksh
Normal file
32
Task/Zig-zag-matrix/Ksh/zig-zag-matrix.ksh
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
#!/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
|
||||
75
Task/Zig-zag-matrix/Lasso/zig-zag-matrix.lasso
Normal file
75
Task/Zig-zag-matrix/Lasso/zig-zag-matrix.lasso
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
var(
|
||||
'square' = array
|
||||
,'size' = integer( 5 )// for a 5 X 5 square
|
||||
,'row' = array
|
||||
,'x' = integer( 1 )
|
||||
,'y' = integer( 1 )
|
||||
,'counter' = integer( 1 )
|
||||
);
|
||||
|
||||
// create place-holder matrix
|
||||
loop( $size );
|
||||
$row = array;
|
||||
|
||||
loop( $size );
|
||||
$row->insert( 0 );
|
||||
|
||||
/loop;
|
||||
|
||||
$square->insert( $row );
|
||||
|
||||
/loop;
|
||||
|
||||
while( $counter < $size * $size );
|
||||
// check downward diagonal
|
||||
if(
|
||||
$x > 1
|
||||
&&
|
||||
$y < $square->size
|
||||
&&
|
||||
$square->get( $y + 1 )->get( $x - 1 ) == 0
|
||||
);
|
||||
|
||||
$x -= 1;
|
||||
$y += 1;
|
||||
|
||||
// check upward diagonal
|
||||
else(
|
||||
$x < $square->size
|
||||
&&
|
||||
$y > 1
|
||||
&&
|
||||
$square->get( $y - 1 )->get( $x + 1 ) == 0
|
||||
);
|
||||
|
||||
$x += 1;
|
||||
$y -= 1;
|
||||
|
||||
// check right
|
||||
else(
|
||||
(
|
||||
$y == 1
|
||||
||
|
||||
$y == $square->size
|
||||
)
|
||||
&&
|
||||
$x < $square->size
|
||||
&&
|
||||
$square->get( $y )->get( $x + 1 ) == 0
|
||||
);
|
||||
|
||||
$x += 1;
|
||||
|
||||
// down
|
||||
else;
|
||||
$y += 1;
|
||||
|
||||
/if;
|
||||
|
||||
$square->get( $y )->get( $x ) = loop_count;
|
||||
|
||||
$counter += 1;
|
||||
|
||||
/while;
|
||||
|
||||
$square;
|
||||
76
Task/Zig-zag-matrix/Lua/zig-zag-matrix.lua
Normal file
76
Task/Zig-zag-matrix/Lua/zig-zag-matrix.lua
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
local zigzag = {}
|
||||
|
||||
function zigzag.new(n)
|
||||
local a = {}
|
||||
local i -- cols
|
||||
local j -- rows
|
||||
|
||||
a.n = n
|
||||
a.val = {}
|
||||
|
||||
for j = 1, n do
|
||||
a.val[j] = {}
|
||||
for i = 1, n do
|
||||
a.val[j][i] = 0
|
||||
end
|
||||
end
|
||||
|
||||
i = 1
|
||||
j = 1
|
||||
|
||||
local di
|
||||
local dj
|
||||
local k = 0
|
||||
|
||||
while k < n * n do
|
||||
a.val[j][i] = k
|
||||
k = k + 1
|
||||
if i == n then
|
||||
j = j + 1
|
||||
a.val[j][i] = k
|
||||
k = k + 1
|
||||
di = -1
|
||||
dj = 1
|
||||
end
|
||||
if j == 1 then
|
||||
i = i + 1
|
||||
a.val[j][i] = k
|
||||
k = k + 1
|
||||
di = -1
|
||||
dj = 1
|
||||
end
|
||||
if j == n then
|
||||
i = i + 1
|
||||
a.val[j][i] = k
|
||||
k = k + 1
|
||||
di = 1
|
||||
dj = -1
|
||||
end
|
||||
if i == 1 then
|
||||
j = j + 1
|
||||
a.val[j][i] = k
|
||||
k = k + 1
|
||||
di = 1
|
||||
dj = -1
|
||||
end
|
||||
i = i + di
|
||||
j = j + dj
|
||||
end
|
||||
|
||||
setmetatable(a, {__index = zigzag, __tostring = zigzag.__tostring})
|
||||
return a
|
||||
end
|
||||
|
||||
function zigzag:__tostring()
|
||||
local s = {}
|
||||
for j = 1, self.n do
|
||||
local row = {}
|
||||
for i = 1, self.n do
|
||||
row[i] = string.format('%d', self.val[j][i])
|
||||
end
|
||||
s[j] = table.concat(row, ' ')
|
||||
end
|
||||
return table.concat(s, '\n')
|
||||
end
|
||||
|
||||
print(zigzag.new(5))
|
||||
48
Task/Zig-zag-matrix/M2000-Interpreter/zig-zag-matrix.m2000
Normal file
48
Task/Zig-zag-matrix/M2000-Interpreter/zig-zag-matrix.m2000
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
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}
|
||||
30
Task/Zig-zag-matrix/M4/zig-zag-matrix.m4
Normal file
30
Task/Zig-zag-matrix/M4/zig-zag-matrix.m4
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
divert(-1)
|
||||
|
||||
define(`set2d',`define(`$1[$2][$3]',`$4')')
|
||||
define(`get2d',`defn(`$1[$2][$3]')')
|
||||
define(`for',
|
||||
`ifelse($#,0,``$0'',
|
||||
`ifelse(eval($2<=$3),1,
|
||||
`pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')')
|
||||
define(`show2d',
|
||||
`for(`x',0,decr($2),
|
||||
`for(`y',0,decr($3),`format(`%2d',get2d($1,x,y)) ')
|
||||
')')
|
||||
|
||||
dnl <name>,<size>
|
||||
define(`zigzag',
|
||||
`define(`j',1)`'define(`k',1)`'for(`e',0,eval($2*$2-1),
|
||||
`set2d($1,decr(j),decr(k),e)`'ifelse(eval((j+k)%2),0,
|
||||
`ifelse(eval(k<$2),1,
|
||||
`define(`k',incr(k))',
|
||||
`define(`j',eval(j+2))')`'ifelse(eval(j>1),1,
|
||||
`define(`j',decr(j))')',
|
||||
`ifelse(eval(j<$2),1,
|
||||
`define(`j',incr(j))',
|
||||
`define(`k',eval(k+2))')`'ifelse(eval(k>1),1,
|
||||
`define(`k',decr(k))')')')')
|
||||
|
||||
divert
|
||||
|
||||
zigzag(`a',5)
|
||||
show2d(`a',5,5)
|
||||
66
Task/Zig-zag-matrix/MATLAB/zig-zag-matrix.m
Normal file
66
Task/Zig-zag-matrix/MATLAB/zig-zag-matrix.m
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
function matrix = zigZag(n)
|
||||
|
||||
%This is very unintiutive. This algorithm parameterizes the
|
||||
%zig-zagging movement along the matrix indicies. The easiest way to see
|
||||
%what this algorithm does is to go through line-by-line and write out
|
||||
%what the algorithm does on a peace of paper.
|
||||
|
||||
matrix = zeros(n);
|
||||
counter = 1;
|
||||
flipCol = true;
|
||||
flipRow = false;
|
||||
|
||||
%This for loop does the top-diagonal of the matrix
|
||||
for i = (2:n)
|
||||
row = (1:i);
|
||||
column = (1:i);
|
||||
|
||||
%Causes the zig-zagging. Without these conditionals,
|
||||
%you would end up with a diagonal matrix.
|
||||
%To see what happens, comment these conditionals out.
|
||||
if flipCol
|
||||
column = fliplr(column);
|
||||
flipRow = true;
|
||||
flipCol = false;
|
||||
elseif flipRow
|
||||
row = fliplr(row);
|
||||
flipRow = false;
|
||||
flipCol = true;
|
||||
end
|
||||
|
||||
%Selects a diagonal of the zig-zag matrix and places the
|
||||
%correct integer value in each index along that diagonal
|
||||
for j = (1:numel(row))
|
||||
matrix(row(j),column(j)) = counter;
|
||||
counter = counter + 1;
|
||||
end
|
||||
end
|
||||
|
||||
%This for loop does the bottom-diagonal of the matrix
|
||||
for i = (2:n)
|
||||
row = (i:n);
|
||||
column = (i:n);
|
||||
|
||||
%Causes the zig-zagging. Without these conditionals,
|
||||
%you would end up with a diagonal matrix.
|
||||
%To see what happens comment these conditionals out.
|
||||
if flipCol
|
||||
column = fliplr(column);
|
||||
flipRow = true;
|
||||
flipCol = false;
|
||||
elseif flipRow
|
||||
row = fliplr(row);
|
||||
flipRow = false;
|
||||
flipCol = true;
|
||||
end
|
||||
|
||||
%Selects a diagonal of the zig-zag matrix and places the
|
||||
%correct integer value in each index along that diagonal
|
||||
for j = (1:numel(row))
|
||||
matrix(row(j),column(j)) = counter;
|
||||
counter = counter + 1;
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
end
|
||||
23
Task/Zig-zag-matrix/Maple/zig-zag-matrix-1.maple
Normal file
23
Task/Zig-zag-matrix/Maple/zig-zag-matrix-1.maple
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
zigzag1:=proc(n)
|
||||
uses ArrayTools;
|
||||
local i,u,v,a;
|
||||
u:=Replicate(<-1,1>,n):
|
||||
v:=Vector[row](1..n,i->i*(2*i-3)):
|
||||
v:=Reshape(<v+~1,v+~2>,2*n):
|
||||
a:=Matrix(n,n):
|
||||
for i to n do
|
||||
a[...,i]:=v[i+1..i+n];
|
||||
v+=u
|
||||
od:
|
||||
a
|
||||
end:
|
||||
|
||||
zigzag2:=proc(n)
|
||||
local i,v,a;
|
||||
a:=zigzag1(n);
|
||||
v:=Vector(1..n-1,i->i^2);
|
||||
for i from 2 to n do
|
||||
a[n+2-i..n,i]-=v[1..i-1]
|
||||
od;
|
||||
a
|
||||
end:
|
||||
1
Task/Zig-zag-matrix/Maple/zig-zag-matrix-2.maple
Normal file
1
Task/Zig-zag-matrix/Maple/zig-zag-matrix-2.maple
Normal file
|
|
@ -0,0 +1 @@
|
|||
zigzag1(6);
|
||||
1
Task/Zig-zag-matrix/Maple/zig-zag-matrix-3.maple
Normal file
1
Task/Zig-zag-matrix/Maple/zig-zag-matrix-3.maple
Normal file
|
|
@ -0,0 +1 @@
|
|||
zigzag2(6);
|
||||
4
Task/Zig-zag-matrix/Mathematica/zig-zag-matrix-1.math
Normal file
4
Task/Zig-zag-matrix/Mathematica/zig-zag-matrix-1.math
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
ZigZag[size_Integer/;size>0]:=Module[{empty=ConstantArray[0,{size,size}]},
|
||||
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]
|
||||
]
|
||||
15
Task/Zig-zag-matrix/Mathematica/zig-zag-matrix-2.math
Normal file
15
Task/Zig-zag-matrix/Mathematica/zig-zag-matrix-2.math
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
ZigZag2[size_] := Module[{data, i, j, elem},
|
||||
data = ConstantArray[0, {size, size}];
|
||||
i = j = 1;
|
||||
For[elem = 0, elem < size^2, elem++,
|
||||
data[[i, j]] = elem;
|
||||
If[Mod[i + j, 2] == 0,
|
||||
If[j < size, j++, i += 2];
|
||||
If[i > 1, i--]
|
||||
,
|
||||
If[i < size, i++, j += 2];
|
||||
If[j > 1, j--];
|
||||
];
|
||||
];
|
||||
data
|
||||
]
|
||||
2
Task/Zig-zag-matrix/Mathematica/zig-zag-matrix-3.math
Normal file
2
Task/Zig-zag-matrix/Mathematica/zig-zag-matrix-3.math
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
ZigZag[5] // MatrixForm
|
||||
ZigZag2[6] // MatrixForm
|
||||
22
Task/Zig-zag-matrix/Maxima/zig-zag-matrix.maxima
Normal file
22
Task/Zig-zag-matrix/Maxima/zig-zag-matrix.maxima
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
zigzag(n) := block([a, i, j],
|
||||
a: zeromatrix(n, n),
|
||||
i: 1,
|
||||
j: 1,
|
||||
for k from 0 thru n*n - 1 do (
|
||||
a[i, j]: k,
|
||||
if evenp(i + j) then (
|
||||
if j < n then j: j + 1 else i: i + 2,
|
||||
if i > 1 then i: i - 1
|
||||
) else (
|
||||
if i < n then i: i + 1 else j: j + 2,
|
||||
if j > 1 then j: j - 1
|
||||
)
|
||||
),
|
||||
a)$
|
||||
|
||||
zigzag(5);
|
||||
/* matrix([ 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]) */
|
||||
9
Task/Zig-zag-matrix/MiniZinc/zig-zag-matrix.minizinc
Normal file
9
Task/Zig-zag-matrix/MiniZinc/zig-zag-matrix.minizinc
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
%Zigzag Matrix. Nigel Galloway, February 3rd., 2020
|
||||
int: Size;
|
||||
array [1..Size,1..Size] of var 1..Size*Size: zigzag;
|
||||
constraint zigzag[1,1]=1 /\ zigzag[Size,Size]=Size*Size;
|
||||
constraint forall(n in {2*g | g in 1..Size div 2})(zigzag[1,n]=zigzag[1,n-1]+1 /\ forall(g in 2..n)(zigzag[g,n-g+1]=zigzag[g-1,n-g+2]+1));
|
||||
constraint forall(n in {2*g + ((Size-1) mod 2) | g in 1..(Size-1) div 2})(zigzag[n,Size]=zigzag[n-1,Size]+1 /\ forall(g in 1..Size-n)(zigzag[n+g,Size-g]=zigzag[n+g-1,Size-g+1]+1));
|
||||
constraint forall(n in {2*g+1 | g in 1..(Size-1) div 2})(zigzag[n,1]=zigzag[n-1,1]+1 /\ forall(g in 2..n)(zigzag[n-g+1,g]=zigzag[n-g+2,g-1]+1));
|
||||
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)];
|
||||
48
Task/Zig-zag-matrix/Modula-3/zig-zag-matrix.mod3
Normal file
48
Task/Zig-zag-matrix/Modula-3/zig-zag-matrix.mod3
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
MODULE ZigZag EXPORTS Main;
|
||||
|
||||
IMPORT IO, Fmt;
|
||||
|
||||
TYPE Matrix = REF ARRAY OF ARRAY OF CARDINAL;
|
||||
|
||||
PROCEDURE Create(size: CARDINAL): Matrix =
|
||||
PROCEDURE move(VAR i, j: INTEGER) =
|
||||
BEGIN
|
||||
IF j < (size - 1) THEN
|
||||
IF (i - 1) < 0 THEN
|
||||
i := 0;
|
||||
ELSE
|
||||
i := i - 1;
|
||||
END;
|
||||
INC(j);
|
||||
ELSE
|
||||
INC(i);
|
||||
END;
|
||||
END move;
|
||||
|
||||
VAR data := NEW(Matrix, size, size);
|
||||
x, y: INTEGER := 0;
|
||||
BEGIN
|
||||
FOR v := 0 TO size * size - 1 DO
|
||||
data[y, x] := v;
|
||||
IF (x + y) MOD 2 = 0 THEN
|
||||
move(y, x);
|
||||
ELSE
|
||||
move(x, y);
|
||||
END;
|
||||
END;
|
||||
RETURN data;
|
||||
END Create;
|
||||
|
||||
PROCEDURE Print(data: Matrix) =
|
||||
BEGIN
|
||||
FOR i := FIRST(data^) TO LAST(data^) DO
|
||||
FOR j := FIRST(data[0]) TO LAST(data[0]) DO
|
||||
IO.Put(Fmt.F("%3s", Fmt.Int(data[i, j])));
|
||||
END;
|
||||
IO.Put("\n");
|
||||
END;
|
||||
END Print;
|
||||
|
||||
BEGIN
|
||||
Print(Create(5));
|
||||
END ZigZag.
|
||||
41
Task/Zig-zag-matrix/NetRexx/zig-zag-matrix.netrexx
Normal file
41
Task/Zig-zag-matrix/NetRexx/zig-zag-matrix.netrexx
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
/* NetRexx */
|
||||
options replace format comments java crossref savelog symbols binary
|
||||
|
||||
zigzag(5)
|
||||
|
||||
return
|
||||
|
||||
method zigzag(msize) public static
|
||||
|
||||
row = 1
|
||||
col = 1
|
||||
|
||||
ziggy = Rexx(0)
|
||||
loop j_ = 0 for msize * msize
|
||||
ziggy[row, col] = j_
|
||||
if (row + col) // 2 == 0 then do
|
||||
if col < msize then -
|
||||
col = col + 1
|
||||
else row = row + 2
|
||||
if row \== 1 then -
|
||||
row = row - 1
|
||||
end
|
||||
else do
|
||||
if row < msize then -
|
||||
row = row + 1
|
||||
else col = col + 2
|
||||
if col \== 1 then -
|
||||
col = col - 1
|
||||
end
|
||||
end j_
|
||||
|
||||
L = (msize * msize - 1).length /*for a constant element width. */
|
||||
loop row = 1 for msize /*show all the matrix's rows. */
|
||||
rowOut = ''
|
||||
loop col = 1 for msize
|
||||
rowOut = rowOut ziggy[row, col].right(L)
|
||||
end col
|
||||
say rowOut
|
||||
end row
|
||||
|
||||
return
|
||||
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