RosettaCodeData/Task/Matrix-transposition/M2000-Interpreter/matrix-transposition.m2000

122 lines
2.7 KiB
Plaintext

Module Matrix_Transpose {
dim a(3,4) as long, b()
a(0,0)=1,2,3,4
a(1,0)=5,6,7,8
a(2,0)=9,10,11,12
open "out.txt" for output as #f
showarray("a()", &a())
b()=@transpose(a())
showarray("transpose to", &b())
dim a(3,1)
a(0,0)=1,2,3
showarray("a()", &a())
b()=@transpose(a())
showarray("transpose to", &b())
// Using arrays with square brackets:
long a[2][0]
// second dimension adjust also from items (for each sub array)
a[0][0]=1,2,3,4
a[1][0]=5,6,7,8
a[2][0]=9,10,11,12
showarray2("a[][]", a)
// transpose has to know the type to define the new one
b=@transposeLong(a)
showarray2("transpose to", b)
long c[2][0]
c[0][0]=1
c[1][0]=2
c[2][0]=3
showarray2("c[]", c)
b=@transposeLong(c)
showarray2("transpose to", b)
' we can use Variant type as return type
d=@transposeAny(b)
showarray2("transpose to", d)
close #f
win "out.txt" ' open out.txt from default application for *.txt files
sub showarray(title$, &a())
print #f, title$+": (";
local boolean z=dimension(a(),1,1)=0
for i=0 to dimension(a(),1,1)
if i>0 then print #f, ", ";
print #f, "(";
if dimension(a(),2,1)>1 then
for j=0 to dimension(a(),2,1)-1
print #f, a(i, j)+", ";
next
print #f, a(i, j)+")";
else
print #f, a(i, 0)+",)";
end if
next
if z then print #f, ",)" else print #f, ")"
end sub
sub showarray2(title$, a as *Long)
' handle with one or zero sub arrays
print #f, title$+": [";
for i=0 to len(a)-1
if i>0 then print #f, ", ";
if valid(len(a[i])) then
print #f, "[";
if len(a[i])>1 then
for j=0 to len(a[i])-2
print #f, a[i][j]+", ";
next
else
j=0
end if
print #f, a[i][j]+"]";
else
print #f, a[i];
end if
next
print #f, "]"
end sub
function transposeLong(a as *long)
Local long R=Len(a)-1 ' upper bound dim 1
Local long L=len(a[0])-1 ' upper bound dim 2
local long b[L][R]
for i=0 to L
for j=0 to R
b[i][j]=a[j][i]
next
next
=b
End Function
function transposeAny(a)
if not valid(a[0][0]) then Error "Wrong Type"
Local long R=Len(a)-1 ' upper bound dim 1
Local long L=len(a[0])-1 ' upper bound dim 2
local Variant b[L][R]
for i=0 to L
for j=0 to R
b[i][j]=a[j][i]
next
next
=b
End Function
function transpose(a as array)
// we use a as pointer to array
// if we use transpose(a()) we get a copy on a()
// so we make one copy only
// copy a to a()
Local a()
a()=a
push &a
Read new &b()
Local long R=dimension(a(),1,1) ' upper bound dim 1
Local long L=dimension(a(),2,1) ' upper bound dim 2
' this is a redim, and preserve the array type also
Dim a(L+1,R+1)
for i=0 to L
for j=0 to R
a(i,j)=b(j, i)
next
next
=a()
End Function
}
Matrix_Transpose