Skip to content

Instantly share code, notes, and snippets.

@vaclavbohac
Created April 23, 2011 10:58
Show Gist options
  • Select an option

  • Save vaclavbohac/938542 to your computer and use it in GitHub Desktop.

Select an option

Save vaclavbohac/938542 to your computer and use it in GitHub Desktop.
matrices.pas
BIN = matrix
matrix: matrix.pas
fpc matrix.pas -o$(BIN)
clean:
rm *.o $(BIN)
program matrices;
{**
* Vaclav Bohac (c) 2011.
* BSD License.
*}
type
matrix = array of array of integer;
{**
* Prints matrix to std. output.
* @param matrix A
*}
procedure print_matrix(A : matrix);
var
i, j, m, n : integer;
begin
m := length(A);
n := length(A[0]);
for i := 0 to m - 1 do
begin
for j := 0 to n - 1 do
begin
write(A[i, j], ' ')
end;
writeln()
end;
end;
{**
* Tests if two matrices have the same dimensions.
* @param matrix A
* @param matrix B
* @return boolean
*}
function test_eq_type(A, B: matrix) : boolean;
var
Am, An, Bm, Bn : integer;
begin
Am := length(A);
An := length(A[0]);
Bm := length(B);
Bn := length(B[0]);
test_eq_type := (Am = Bm) AND (An = Bn)
end;
{**
* Adds two equaly sized matrices.
* @param matrix A
* @param matrix B
* @return integer
*}
function add_matrices(A, B: matrix) : matrix;
var
C : matrix;
i, j, m, n : integer;
begin
m := length(A);
n := length(A[0]);
SetLength(C, m, n);
for i := 0 to m - 1 do
begin
for j := 0 to n - 1 do
begin
C[i, j] := A[i, j] + B[i, j]
end
end;
add_matrices := C
end;
var
A, B : matrix;
i, j, m, n : integer;
begin {* entry point *}
m := 5;
n := m;
setlength(A, m, n);
setlength(B, m, n);
for i := 0 to m - 1 do
begin
for j := 0 to n - 1 do
begin
A[i, j] := i;
B[i, j] := j
end
end;
if not test_eq_type(A, B) then
writeln('Types are not equal')
else begin
print_matrix(A);
writeln();
print_matrix(B);
writeln();
print_matrix(add_matrices(A, B))
end;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment