How to find the element with minimum occurrences in an array with Pascal

1 Answer

0 votes
program MinOccurrenceExample;

{$mode objfpc}{$H+}

uses
  SysUtils, Generics.Collections;

type
  TIntArray = array of Integer;

// Function to find the element with minimum occurrences in an integer array
function FindMinOccurrence(const Arr: TIntArray; out MinElem: Integer): Boolean;
var
  SortedArr: TIntArray;
  I: Integer;
  CurrentCount, MinCount: Integer;
begin
  // Check for empty input array
  if Length(Arr) = 0 then
    Exit(False);

  // 1. Create a copy of the original array to preserve source data
  SetLength(SortedArr, Length(Arr));
  for I := 0 to High(Arr) do
    SortedArr[I] := Arr[I];

  // 2. Sort using specialized TArrayHelper in Free Pascal
  specialize TArrayHelper<Integer>.Sort(SortedArr);

  // 3. Single pass to count consecutive runs
  MinElem := SortedArr[0];
  MinCount := Length(SortedArr) + 1; // Initialize higher than any possible count
  CurrentCount := 1;

  for I := 1 to Length(SortedArr) do
  begin
    // Check if current element matches previous element
    if (I < Length(SortedArr)) and (SortedArr[I] = SortedArr[I - 1]) then
    begin
      Inc(CurrentCount);
    end
    else
    begin
      // Reached end of a group: update min tracker if count is smaller
      if CurrentCount < MinCount then
      begin
        MinCount := CurrentCount;
        MinElem := SortedArr[I - 1];
      end;
      CurrentCount := 1; // Reset count for next group
    end;
  end;

  Result := True; // Success
end;

var
  arr: TIntArray;
  ResultVal: Integer;
begin
  // Initialize the array
  SetLength(arr, 15);
  arr[0] := 1; arr[1] := 3; arr[2] := 1; arr[3] := 1; arr[4] := 4;
  arr[5] := 4; arr[6] := 5; arr[7] := 5; arr[8] := 4; arr[9] := 2;
  arr[10] := 2; arr[11] := 2; arr[12] := 3; arr[13] := 3; arr[14] := 3;

  if FindMinOccurrence(arr, ResultVal) then
    WriteLn(ResultVal) // Output: 5
  else
    WriteLn('Array is empty!');
end.


{
run:

5

}

 



answered Sep 25 by avibootz
edited Sep 25 by avibootz
...