Determine the number of unique values ​​in an array

I am looking for an effective way to determine the number of unique values ​​in an array.

My current approach:

  • Fast array of integer arrays
  • Then run a loop to compare the elements.

In code:

  yearHolder := '';
  for I := 0 to  High(yearArray) do
  begin
    currYear := yearArray[i];
    if (yearHolder <> currYear) then
    begin
      yearHolder := currYear;
      Inc(uniqueYearNumber);
    end;
  end;
+3
source share
6 answers

Here is an example with THashedStringList:

hl := THashedStringList.Create; // in Inifiles
try
  hl.Sorted := True;
  hl.Duplicates := dupIgnore; // ignores attempts to add duplicates
  for i := 0 to  High(yearArray) do
    hl.Add(yearArray[i]);
  uniqueYearCount := hl.Count;
finally
  hl.Free;
end;
+6
source

In general, you can use this algorithm:

  • Create a hash table that maps the year to the number of occurrences.
  • For each number in your array, put the corresponding entry in the hash table.
  • When done, get the number of entries in the hash.

"". , , . , 0-3000 . , - . 0s. , 2009 , arr [2009]. arr [i] >= 1.

+4

: .

D2009 THashedStringList ( → ), D2009, . .

0

Delphi, DeHL, : uniqueWidgets: = List.Create(MassiveListOfNonUniqueWidgets.Distinct());

:

0

Set , , Set. , Java, DDL,.Net ( ), , .

-1

A more efficient algorithm would be to dump the entire hash table (not sure if Delphi even has this).

  • Go through the list (in this case yearArray) and use the values ​​as keys in the hash table.
  • Get the number of keys in a hash table.
-2
source

Source: https://habr.com/ru/post/1710370/


All Articles