Next: Records Up: Data Structures Previous: Tables

Arrays

A one-dimensional array is created using the array command

array( .. );

This creates an array with indices . Often is 1. Entries can be inserted into the array by assignment as for tables, e.g.


v := array(1..n);
v[1] := a;
for i from 2 to n do v[i] := a*v[i-1] mod n od;

One-dimensional arrays are like tables with one index which is restricted to be in a fixed integer range. Arrays are more efficient to access than tables and range checking on the indices is done. Here is an example of a one-dimensional array used to sort a sequence of numbers. For instance, suppose we are given an array = array(1..n) as above. The code presented here sorts into ascending order using the bubblesort algorithm:


for i to n-1 do
    for j from i+1 to n do
        if v[i] > v[j] then temp := v[i]; v[i] := v[j]; v[j] := temp fi
    od
od;

Another application of one-dimensional arrays is as an intermediate data structure. For example, suppose we represent a polynomial as a list of coefficients. Suppose we are given also a polynomial of degree . We can use an array to compute the product as follows


m := nops(a)-1; # degree of a
n := nops(b)-1; # degree of b
c := array(0..m+n); # allocate storage for the product
for i from 0 to m+n do c[i] := 0 od;
for i from 0 to m do
    for j from 0 to n do
        c[i+j] := c[i+j] + a[i+1]*b[j+1]
    od
od:
[seq(c[i],i=0..n+m)]; # put the product in a list

Two-dimensional arrays, and higher dimensional arrays work similarly. A two-dimensional array is created by the command

array( , .. );

As an example, suppose we are given the vector of symmetric polynomials in variables .


v := array(1..4):
v[1] := 1:
v[2] := x[1] + x[2] + x[3]:
v[3] := x[1]*x[2] + x[1]*x[3] + x[2]*x[3]:
v[4] := x[1]*x[2]*x[3]:

Let us construct a two-dimensional array , where is the derivative of wrt .


> M := array(1..4,1..3):
> for i to 4 do for j to 3 do M[i,j] := diff(v[i],x[j]) od od:
> M;
                                       M

> eval(M);
                   [      0            0            0      ]
                   [                                       ]
                   [      1            1            1      ]
                   [                                       ]
                   [ x[2] + x[3]  x[1] + x[3]  x[1] + x[2] ]
                   [                                       ]
                   [  x[2] x[3]    x[1] x[3]    x[1] x[2]  ]

For further information on arrays see ?array . Note also that one-dimensional arrays indexed from 1 are used to represent vectors and two-dimensional arrays indexed from 1 are used to represent matrices. See the section on Matrices and Vectors.


bondaren@thsun1.jinr.ru