arraysdelphiunique

Delphi: check if values in array (or values of variables) are unique at one time


I need to check if values of some variables are unique. This is a sample/example for 4 variables, but i'm looking for something universal so that it works for 3, 5 and so on variables. I can make a code comparing variables like this:

var
  A, B, C, D : Integer;
begin
  ...
  if(A <> B) and (B <> C) and (C <> B) and ... then
    ShowMessage('are unique');
end;

Is there a shorter way to compare all values? I mean something like:

var
  A, B, C, D : Integer;
begin
  ...
  if UniqueValues([A, B, C, D]) then
    ShowMessage('are unique');
end;

Solution

  • Such a function could simply be written like this:

    function UniqueValues(const Values: array of Integer ): Boolean;
    var
      I: Integer;
      J: Integer;
    begin
      for I := Low(Values) to High(Values) - 1 do
        for J := I + 1 to High(Values) do
          if Values[I] = Values[J]  then
            Exit(False);
      Result := True;
    end;