Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: printing largest hash value

by thedoe (Monk)
on Feb 22, 2005 at 03:42 UTC ( [id://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?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (2)
As of 2024-04-25 20:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found