Skip to content

Latest commit

 

History

History
98 lines (71 loc) · 2.69 KB

File metadata and controls

98 lines (71 loc) · 2.69 KB

OccurrencesOf<T> class method

Project: Array Utilities Unit

Unit: DelphiDabbler.Lib.ArrayUtils

Record: TArrayUtils

Applies to: ~>0.1

class function OccurrencesOf<T>(const AItem: T; const A: array of T;
  const AEqualityComparer: TEqualityComparison<T>): Integer;
  overload; static;

class function OccurrencesOf<T>(const AItem: T; const A: array of T;
  const AEqualityComparer: IEqualityComparer<T>): Integer;
  overload; static;

class function OccurrencesOf<T>(const AItem: T;
  const A: array of T): Integer;
  overload; static;

Description

Returns the number of elements of an array that are equal to a given value.

Parameters:

  • AItem - The item to be searched for.

  • A - The array to be searched.

  • AEqualityComparer - An optional function or object that is used to test the equality of two values. Used to test AItem for equality with elements of A.

    If AEqualityComparer is provided it must be one of:

    If the parameter is omitted then the default equality comparer defined by Delphi's TEqualityComparer<T>.Default method is used.

Returns:

  • The number of matching elements of A.

Examples

Example #1

Using an equality comparer function:

procedure OccurrencesOf_Eg1;
var
  A: TArray<Integer>;
  EqComparerFn: TEqualityComparison<Integer>;
begin
  A := TArray<Integer>.Create(1, 2, 3, 4, 2, 3, 2);
  EqComparerFn := function(const Left, Right: Integer): Boolean
    begin
      Result := Left = Right;
    end;
  Assert(TArrayUtils.OccurrencesOf<Integer>(2, A, EqComparerFn) = 3);
  Assert(TArrayUtils.OccurrencesOf<Integer>(5, A, EqComparerFn) = 0);
end;

Example #2

Using an equality comparer object:

procedure OccurrencesOf_Eg2;
var
  A: TArray<string>;
  EqComparerObj: IEqualityComparer<string>;
begin
  A := TArray<string>.Create('A', 'B', 'C', 'd', 'c', 'a');
  EqComparerObj := TDelegatedEqualityComparer<string>.Create(
    SameText,
    function(const Value: string): Integer
    begin
      // only do this if you KNOW the hash function won't be called
      Result := 0;
    end
  );
  Assert(TArrayUtils.OccurrencesOf<string>('C', A, EqComparerObj) = 2);
  Assert(TArrayUtils.OccurrencesOf<string>('x', A, EqComparerObj) = 0);
end;

See Also