Search code examples
delphidelphi-6

How to set multiple array fields at once without using a for loop in pascal?


I am learning Pascal and currently stuck with a problem concerning array manipulation. I have come across a method of setting arrays, that I have seen in other languges, but I do not know how to do something similar in Pascal.

The declaration of the variable looks something like this:

rotationBounds: array of array of integer;
setLength(rotationBounds, 5, 5);

And I want to do something like this:

 rotationBounds :=
         [
          [0, 0, 0, 0, 0],
          [0, 1, 1, 0, 0],
          [0, 0, 1, 0, 0],
          [0, 0, 1, 1, 0],
          [0, 0, 0, 0, 0],
         ]; 

Basically, I am trying to set a multi-dimentional array directly, rather than looping through it.

One of my focuses is to make it look like a picture, easy to read and understand.

Is there a way I could achieve something like this?

I am using Borland Delphi 6 to compiler the progam.


Solution

  • In Delphi 6 there is no built in support for dynamic array initialization. I'd use a pair of helper functions for this:

    type
      TIntegerArray = array of Integer;
      TIntegerMatrix = array of TIntegerArray;
    
    function IntegerArray(const Values: array of Integer): TIntegerArray;
    var
      i: Integer;
    begin
      SetLength(Result, Length(Values));
      for i := 0 to high(Result) do
        Result[i] := Values[i];
    end;
    
    function IntegerMatrix(const Values: array of TIntegerArray): TIntegerMatrix;
    var
      i: Integer;
    begin
      SetLength(Result, Length(Values));
      for i := 0 to high(Result) do
        Result[i] := Values[i];
    end;
    

    And then call it like this:

    var
      rotationBounds: TIntegerMatrix;
    ....
    rotationBounds := IntegerMatrix([
      IntegerArray([0, 0, 0, 0, 0]),
      IntegerArray([0, 1, 1, 0, 0]),
      IntegerArray([0, 0, 1, 0, 0]),
      IntegerArray([0, 0, 1, 1, 0]),
      IntegerArray([0, 0, 0, 0, 0]),
    ]);