Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is best way to Find the max value in a delphi TDictionary?

i have a TDictionary declared like so TDictionary<String,Integer>, Now i want to get the max of the value stored in the TDictionary. i can do this iterating over the TDictionary and comparing the values, but I'm wondering exist a better way to do this? exist any function or maybe the dictionary can be sorted by the values to retrieve the max value stored?

this is which i'am doing now

var
   MyDict       : TDictionary<String,Integer>;
   MaxValue, i  : Integer;
begin
   MyDict:=TDictionary<String,Integer>.Create;
   try    
     MyDict.Add('this',1);
     MyDict.Add('is',7);
     MyDict.Add('a',899);
     MyDict.Add('sample',1000);
     MyDict.Add('finding',12);
     MyDict.Add('the',94);
     MyDict.Add('max',569);
     MyDict.Add('value',991);

     MaxValue:=MyDict.ToArray[0].Value;
     for i in MyDict.Values do
      if i>MaxValue then MaxValue:=i;

     ShowMessage(Format('The max value is %d',[MaxValue]));
   finally
     MyDict.Free;
   end;
end;
like image 842
Salvador Avatar asked May 04 '11 02:05

Salvador


1 Answers

I haven't used this particular class, but the excellent Delphi Collections 1.1.1. has a class TDoubleSortedBidiDictionary which has sorted values.

When to use: This bidirectional dictionary implementation uses two AVL trees. Use it if you care about keys and values being sorted.

btw, if you are "storing the number of occurences of each word", have a look at TBag from Delphi Collections. It is a Delphi implementation of MultiSet.

like image 80
awmross Avatar answered Sep 23 '22 23:09

awmross