How to create a common sorted unique array from 3 integer arrays in Pascal

1 Answer

0 votes
program MergeUniqueSorted;

{$mode objfpc}

type
  // Define a dynamic integer array type 
  TIntegerDynArray = array of Integer;

(*
   Procedure: SortIntArray
   Purpose:   Sort a dynamic integer array in ascending order (simple bubble sort).
*)
procedure SortIntArray(var A: TIntegerDynArray);
var
  i, j, tmp: Integer;
begin
  for i := 0 to High(A) do
    for j := 0 to High(A) - 1 - i do
      if A[j] > A[j + 1] then
      begin
        tmp := A[j];
        A[j] := A[j + 1];
        A[j + 1] := tmp;
      end;
end;

(*
   Function: MergeArrays
   Purpose:  Combine three integer arrays into one dynamic array.
*)
function MergeArrays(const A, B, C: array of Integer): TIntegerDynArray;
var
  total, i, idx: Integer;
begin
  total := Length(A) + Length(B) + Length(C);
  SetLength(Result, total);

  idx := 0;

  for i := 0 to High(A) do
  begin
    Result[idx] := A[i];
    Inc(idx);
  end;

  for i := 0 to High(B) do
  begin
    Result[idx] := B[i];
    Inc(idx);
  end;

  for i := 0 to High(C) do
  begin
    Result[idx] := C[i];
    Inc(idx);
  end;
end;

(*
   Function: UniqueSorted
   Purpose:  Sort an array and remove duplicate values.
*)
function UniqueSorted(arr: TIntegerDynArray): TIntegerDynArray;
var
  i, count: Integer;
begin
  // Sort the array 
  SortIntArray(arr);

  // Allocate maximum possible size 
  SetLength(Result, Length(arr));
  count := 0;

  for i := 0 to High(arr) do
  begin
    if (i = 0) or (arr[i] <> arr[i - 1]) then
    begin
      Result[count] := arr[i];
      Inc(count);
    end;
  end;

  // Trim to actual number of unique elements 
  SetLength(Result, count);
end;

var
  arr1: TIntegerDynArray = (5, 1, 14, 3, 8, 9, 1, 1, 7);
  arr2: TIntegerDynArray = (3, 5, 7, 2, 3);
  arr3: TIntegerDynArray = (2, 9, 8);

  merged, unique: TIntegerDynArray;
  i: Integer;

begin
  // Step 1: Merge arrays 
  merged := MergeArrays(arr1, arr2, arr3);

  // Step 2: Sort and remove duplicates 
  unique := UniqueSorted(merged);

  // Step 3: Print result 
  Write('Sorted unique array: ');
  for i := 0 to High(unique) do
    Write(unique[i], ' ');
  WriteLn;
end.



(*
run:

Sorted unique array: 1 2 3 5 7 8 9 14 

*)

 



answered May 6 by avibootz

Related questions

...