¿Cómo implementar operaciones matriciales en Pascal?
Pregunta
Necesito implementar operaciones con matrices y el tamaño de la matriz debe ser variable. La única solución que se me ocurrió es usar la lista vinculada:
[pointer to this row, pointer to another row] -> [element 1,1; link to another element] -> [element 1,2, link to another element] -> .... -> [nil]
|
v
[pointer to this row, pointer to another row] ...
...
Pero me parece un poco complejo. ¿Existe una solución mejor (y más fácil)?
¡Gracias chicos!
Solución
Un enfoque sería utilizar GetMem para asignar exactamente suficiente memoria. GetMem parece ampliamente compatible.
const
MAXMATRIXDATA: Word = 10000;
type
TMatrixDataType = Word;
TMatrixData = array[0..MAXMATRIXDATA] of TMatrixDataType;
PMatrixData = ^TMatrixData;
TMatrix = record
Rows, Cols: Word;
MatrixData: PMatrixData;
end;
PMatrix = ^TMatrix;
function CreateMatrix(Rows, Cols: Word): PMatrix;
var
Ret: PMatrix;
begin
New(Ret);
Ret^.Rows := Rows;
Ret^.Cols := Cols;
GetMem(Ret^.MatrixData,Rows*Cols*SizeOf(TMatrixDataType));
CreateMatrix := Ret;
end;
function GetMatrixData(Matrix: PMatrix; Row, Col: Word): TMatrixDataType;
begin
GetMatrixData := Matrix^.MatrixData^[(Row*Matrix^.Cols)+Col];
end;
procedure SetMatrixData(Matrix: PMatrix; Row, Col: Word; Val: TMatrixDataType);
begin
Matrix^.MatrixData^[(Row*Matrix^.Cols)+Col] := Val;
end;
Otros consejos
Cualquier variante pascal moderna (Delphi) le permitirá crear arreglos dinámicos (tamaño de tiempo de ejecución).
Si el lenguaje no admite matrices dinámicas multidimensionales, puede encargarse del direccionamiento usted mismo:
var
rows, cols, total, i, j : integer;
cell : datatype;
begin
rows := ...;
cols := ...;
total := rows * cols;
matrix := ...(total);
cell := matrix[i * cols + j]; // matrix[row=i,col=j]
end;
Este tipo de direccionamiento será mucho más rápido que seguir listas enlazadas.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow