What is the easiest way to get a key with the highest value from a hash in Perl?
相关问题
- facebook error invalid key hash for some devices
- $ENV{$variable} in perl
- Is it possible to pass command-line arguments to @
- Redirecting STDOUT and STDERR to a file, except fo
- Change first key of multi-dimensional Hash in perl
相关文章
- Bcrypt vs Hash in laravel
- Running a perl script on windows without extension
- Comparing speed of non-matching regexp
- Can NOT List directory including space using Perl
- Extracting columns from text file using Perl one-l
- Lazy (ungreedy) matching multiple groups using reg
- How do I tell DBD::mysql where mysql.sock is?
- What is a good way to deploy a Perl application?
Not sure why everyone is doing this by hand...
While the solution with sort:
found in some of the other answers is quite elegant, it doesn't perform as nicely as it looks. First off, the sort transforms an
O(n)
search search operation into anO(n log n)
one. Secondly, the sort solution hasn log n
hash look-ups. Hash look-ups are very good for certain operations, but when working with the entire hash, look-ups will be slower than usingeach
,keys
, orvalues
to iterate through the data structure. This is because the iterators do not need to calculate the hashes of keys, nor do they need to repeatedly walk through bins to find the values. And the overhead is not constant, but increasing as the hashes get larger.Here are a few faster solutions:
Here is a solution using the
each
iterator (anO(1)
operation donen
times):Or a faster version that trades memory for speed (it makes a copy of the hash):
Here is the performance with various hash sizes:
As you can see, if memory isn't much of an issue, the version with internal arrays is fastest, closely followed by the
each
iterator, and in a distant third...sort
The keys sorted by value, from lowest to highest:
The keys sorted by value, from highest to lowest:
And the first element
Replace the spaceship with
cmp
to taste.The following is more space-efficient and will run in O(n) instead of O(n log n) as compared to the other answers which sort the hash. It assumes values are integers greater than 0 and the hash is not empty, but should be easily extended for your case.
$key_for_max_value will now be the key corresponding to the highest value.
If performance isn't an issue, I'd suggest a more literate programming solution.