Skip to content

Latest commit

 

History

History
95 lines (67 loc) · 2.45 KB

File metadata and controls

95 lines (67 loc) · 2.45 KB

MinMax<T> class method

Project: Array Utilities Unit

Unit: DelphiDabbler.Lib.ArrayUtils

Record: TArrayUtils

Applies to: ~>0.1

class procedure MinMax<T>(const A: array of T;
  const AComparer: TComparison<T>; out AMinValue, AMaxValue: T);
  overload; static;

class procedure MinMax<T>(const A: array of T;
  AComparer: IComparer<T>; out AMinValue, AMaxValue: T);
  overload; static;

class procedure MinMax<T>(const A: array of T; out AMinValue, AMaxValue: T);
  overload; static;

Description

Finds the minimum and maximum values of a non empty array.

Parameters:

  • A - The array to be examined.

  • AComparer - An optional function or object that can be used to compare two values. Used to compare the elements of the arrays to each other.

    If AComparer is provided it must be one of:

    If this parameter is omitted then the default comparer defined by the TComparer<T>.Default method from the Delphi's System.Generics.Defaults unit is used.

  • MinValue - Set to the minimum value of A when the method returns.

  • MaxValue - Set to the maximum value of A when the method returns.

Precondition:

  • A must not be empty. An EAssertionFailed exception is raised otherwise.

Examples

Example #1

Using an equality comparer function:

procedure MinMax_Eg1;
var
  A: TArray<Integer>;
  MinVal, MaxVal: Integer;
  ComparerFn: TComparison<Integer>;
begin
  A := TArray<Integer>.Create(1, 2, 3, 4, 2, 3, 2);
  ComparerFn := function(const Left, Right: Integer): Integer
    begin
      Result := Left - Right;
    end;
  TArrayUtils.MinMax<Integer>(A, ComparerFn, MinVal, MaxVal);
  Assert(MinVal = 1);
  Assert(MaxVal = 4);
end;

Example #2

Using an equality comparer object:

procedure MinMax_Eg2;
var
  A: TArray<string>;
  MinVal, MaxVal: string;
  ComparerObj: IComparer<string>;
begin
  A := TArray<string>.Create('a', 'b', 'c', 'd', 'c', 'a');
  ComparerObj := TDelegatedComparer<string>.Create(CompareStr);
  TArrayUtils.MinMax<string>(A, ComparerObj, MinVal, MaxVal);
  Assert(MinVal = 'a');
  Assert(MaxVal = 'd');
end;

See Also