Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: printing largest hash value

by thedoe (Monk)
on Feb 22, 2005 at 03:42 UTC ( #433236=note: print w/replies, xml ) Need Help??


in reply to printing largest hash value

Why not just do the simple way:

my %hash = ( red => 2, pink => 1, orange => 4, black => 3, blue => 4 ); my ($max, @maxKeys); for (keys %hash) { $max = $hash{$_} unless $max; if ($hash{$_} > $max) { @maxKeys = ($_); $max = $hash{$_}; } elsif ($hash{$_} == $max) { push @maxKeys, $_; } } print "$_: $hash{$_}\n" for @maxKeys;

This will only touch each value once, which is necessary anyway for this type of problem, giving you a O(N) solution.

Update: My bad, didn't see the part about printing the keys and values, so I have updated my code accordingly.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (2)
As of 2022-01-23 13:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:












    Results (63 votes). Check out past polls.

    Notices?