Project: Array Utilities Unit
Unit: DelphiDabbler.Lib.ArrayUtils
Record: TArrayUtils
Applies to: ~>0.1
class function IndicesOf<T>(const AItem: T; const A: array of T;
const AEqualityComparer: TEqualityComparison<T>): TArray<Integer>;
overload; static;
class function IndicesOf<T>(const AItem: T; const A: array of T;
const AEqualityComparer: IEqualityComparer<T>): TArray<Integer>;
overload; static;
class function IndicesOf<T>(const AItem: T;
const A: array of T): TArray<Integer>;
overload; static;Returns the indices of all 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:
- A function of type TEqualityComparison<T>.
- An object that supports the IEqualityComparer<T> interface.
If the parameter is omitted then the default equality comparer defined by Delphi's TEqualityComparer<T>.Default method is used.
Returns:
- Integer array containing all the found indexes. The array will be empty if AItem is not equal to any element of A.
Get the indices of all elements of a byte array that are equal to a given byte value. We use an equality comparer function in this code.
procedure IndicesOf_Eg1;
var
A: TArray<Byte>;
Got, Expected: TArray<Integer>;
EqComparerFn: TEqualityComparison<Byte>;
begin
EqComparerFn := function (const L, R: Byte): Boolean
begin
Result := L = R;
end;
A := TArray<Byte>.Create(0, 3, 2, 1, 2, 3, 1, 3, 3);
Got := TArrayUtils.IndicesOf<Byte>(3, A, EqComparerFn);
Expected := TArray<Integer>.Create(1, 5, 7, 8);
Assert(TArrayUtils.Equal<Integer>(Expected, Got));
Got := TArrayUtils.IndicesOf<Byte>(4, A, EqComparerFn);
Expected := TArray<Integer>.Create();
Assert(TArrayUtils.Equal<Integer>(Expected, Got));
end;Get the indices of all elements of a string array that are the same as a given string, ignoring case. We use an equality comparer object in this code.
procedure IndicesOf_Eg2;
var
A: TArray<string>;
Got, Expected: TArray<Integer>;
EqComparer: IEqualityComparer<string>;
begin
EqComparer := TDelegatedEqualityComparer<string>.Create(
SameText,
function (const AValue: string): Integer
begin
// Don't do this unless you KNOW the hasher function won't be called
Result := 0;
end
);
A := TArray<string>.Create('foo', 'FOO', 'bar', 'baz', 'Foo');
Got := TArrayUtils.IndicesOf<string>('foo', A, EqComparer);
Expected := TArray<Integer>.Create(0, 1, 4);
Assert(TArrayUtils.Equal<Integer>(Expected, Got));
end;