How to flatten a 2D array into a sorted one-dimensional array in Pascal

1 Answer

0 votes
program FlattenAndSort;

{$mode objfpc}{$H+}

// Define types for our dynamic arrays
type
  T2DIntArray = array of array of Integer;
  T1DIntArray = array of Integer;

{-------------------------------------------------------------------------------
  Function to flatten a 2D array and sort the resulting 1D array
-------------------------------------------------------------------------------}
function FlattenAndSortArray(const Arr2D: T2DIntArray): T1DIntArray;
var
  i, j, TotalLength, CurrentIndex: Integer;
  Temp: Integer;
begin
  Result := nil;  

  TotalLength := 0;
  
  // 1. Calculate the total number of elements across all rows
  for i := 0 to High(Arr2D) do
    TotalLength := TotalLength + Length(Arr2D[i]);
    
  // Set the length of our output 1D array
  SetLength(Result, TotalLength);
  
  // 2. Flatten the array by copying elements row by row
  CurrentIndex := 0;
  for i := 0 to High(Arr2D) do
  begin
    for j := 0 to High(Arr2D[i]) do
    begin
      Result[CurrentIndex] := Arr2D[i][j];
      Inc(CurrentIndex);
    end;
  end;
  
  // 3. Sort the 1D array using Insertion Sort
  for i := 1 to High(Result) do
  begin
    Temp := Result[i];
    j := i - 1;

    while (j >= 0) and (Result[j] > Temp) do
    begin
      Result[j + 1] := Result[j];
      j := j - 1;
    end;

    Result[j + 1] := Temp;
  end;
end;

var
  Array2D: T2DIntArray;
  Array1D: T1DIntArray;
  i: Integer;

begin
  // Initialize the jagged 2D array as specified
  SetLength(Array2D, 4);
  
  Array2D[0] := T1DIntArray.Create(4, 5, 3);
  Array2D[1] := T1DIntArray.Create(30, 20);
  Array2D[2] := T1DIntArray.Create(10);
  Array2D[3] := T1DIntArray.Create(1, 2, 6, 7, 8);

  // Process the array
  Array1D := FlattenAndSortArray(Array2D);

  // Print the sorted 1D array
  Write('Sorted 1D Array: [');
  for i := 0 to High(Array1D) do
  begin
    Write(Array1D[i]);
    if i < High(Array1D) then
      Write(', ');
  end;
  Writeln(']');
end.



(*
run:

[1, 2, 3, 4, 5, 6, 7, 8, 10, 20, 30]

*)

 



answered 2 hours ago by avibootz

Related questions

...