Como implementar as operações de matrizes em Pascal?
Pergunta
Eu preciso implementar operações com matrizes e tamanho da matriz tem que ser variável. A única solução que eu vim com é usar lista ligada:
[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] ...
...
Mas parece-me um pouco complexo .. Existe uma solução melhor (e mais fácil)?
Obrigado rapazes!
Solução
Uma abordagem seria usar GetMem para alocar memória exatamente o suficiente. GetMem parece amplamente suportado.
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;
Outras dicas
Qualquer variante pascal moderna (Delphi) vai deixar você criar dinâmico (tempo de execução de calibragem), arrays.
Se o idioma não suporta matrizes dinâmicas multidimensionais você pode cuidar do abordando-se:
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 abordagem será muito mais rápido do que seguir listas ligadas.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow