Author: Jonas Bilinkevicius
I'm working with a matrix and I've chosen to use an Array of Array of real to do it
(Is it the best way? I need the elements to be of real type). The problem is that I
must change a certain line with another. For example, change the first line of the
matrix with the second one. How do I do it quickly? I don't want to move element by
element.
Answer:
1 program Matrices;
2 3 {$APPTYPE CONSOLE}4 5 uses6 SysUtils;
7 8 type9 TMatrixRow = arrayof Double; {preferrable to Real}10 TMatrix = arrayof TMatrixRow;
11 12 procedure MatrixExchangeRows(M: TMatrix; First, Second: Integer);
13 var14 Help: TMatrixRow;
15 begin16 if (First < 0) or (First > High(M)) or (Second < 0) or (Second > High(M)) then17 Exit; {or whatever you like.}18 {Only pointers are exchanged!}19 Help := M[First];
20 M[First] := M[Second];
21 M[Second] := Help;
22 end;
23 24 procedure MatrixWrite(M: TMatrix);
25 var26 Row, Col: Integer;
27 begin28 for Row := 0 to High(M) do29 begin30 for Col := 0 to High(M[Row]) do31 write(M[Row, Col]: 10: 2);
32 Writeln;
33 end;
34 Writeln;
35 end;
36 37 var38 Matrix: TMatrix;
39 Row, Column: Integer;
40 41 begin42 Randomize;
43 SetLength(Matrix, 4, 4);
44 for Row := 0 to High(Matrix) do45 for Column := 0 to High(Matrix[Row]) do46 Matrix[Row, Column] := Random * 1000.0;
47 MatrixWrite(Matrix);
48 MatrixExchangeRows(Matrix, 1, 2);
49 MatrixWrite(Matrix);
50 Readln;
51 end.