Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re: printing largest hash value

by brian_d_foy (Abbot)
on Feb 22, 2005 at 04:06 UTC ( #433244=note: print w/replies, xml ) Need Help??

in reply to printing largest hash value

Not that there is anything wrong with the other solutions, but here is another one. I sort the keys by values, then use a while loop to figure out where the highest value ends in the list of sorted keys, @keys. Once I know that, I slice @keys to get the right keys.

#!/usr/bin/perl my %h = ( red => 2, pink => 1, orange => 4, black => 3, blue => 4, green => 3, ); my $i = 0; my @keys = sort { $h{$b} <=> $h{$a} } keys %h; 1 while( $h{$keys[++$i]} == $h{$keys[0]} ); my @largest = @keys[0..$i-1]; print qq|Largest are "@largest"\n|;

I had a solution that used grep, but that's stupid since I don't need to go through the rest of the elements once I know I've seen the highest ones.

#!/usr/bin/perl use strict; my %h = ( red => 2, pink => 1, orange => 4, black => 3, blue => 4, ); my @keys = sort { $h{$b} <=> $h{$a} } keys %h; my @largest = grep { $h{$_} == $h{$keys[0]} } @keys; print qq|Largest are "@largest"\n|;
brian d foy <>

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://433244]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2022-01-26 13:37 GMT
Find Nodes?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:

    Results (69 votes). Check out past polls.