How to find the maximum distance between two numbers in an array with Pascal

1 Answer

0 votes
program MaxDistanceProgram;

{$mode objfpc}{$H+}

type
  TIntArray = array of Integer;

{
  Finds the maximum distance between two values in an array.

  Distance = Abs(IndexA - IndexB)

  Returns:
    - Maximum distance if both values exist.
    - -1 if one or both values are not found.
}
function MaxDistanceBetweenValues(const Arr: TIntArray;
                                  Value1, Value2: Integer): Integer;
var
  I: Integer;
  First1, Last1: Integer;
  First2, Last2: Integer;
  Distance1, Distance2: Integer;
begin
  First1 := -1;
  Last1  := -1;

  First2 := -1;
  Last2  := -1;

  { Find first and last occurrences of both values }
  for I := 0 to High(Arr) do
  begin
    if Arr[I] = Value1 then
    begin
      if First1 = -1 then
        First1 := I;

      Last1 := I;
    end;

    if Arr[I] = Value2 then
    begin
      if First2 = -1 then
        First2 := I;

      Last2 := I;
    end;
  end;

  { Check if both values were found }
  if (First1 = -1) or (First2 = -1) then
    Exit(-1);

  { Compare both extreme distances }
  Distance1 := Abs(First1 - Last2);
  Distance2 := Abs(First2 - Last1);

  if Distance1 > Distance2 then
    Result := Distance1
  else
    Result := Distance2;
end;

var
  Arr: TIntArray;
  Distance: Integer;
begin
  Arr := TIntArray.Create(
    2, 3, 7, 3, 3, 4, 8, 8, 8, 11, 9, 1, 3
  );

  Distance := MaxDistanceBetweenValues(Arr, 3, 8);

  WriteLn('Maximum distance between 3 and 8: ', Distance);
end.


{
run:

Maximum distance between 3 and 8: 7

}

 



answered Oct 22 by avibootz

Related questions

...