Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: find maximum occuring element in a array

by zentara (Archbishop)
on Sep 07, 2011 at 16:59 UTC ( [id://924626]=note: print w/replies, xml ) Need Help??


in reply to find maximum occuring element in a array

How can I get QS as result?

Looking for somethings like this? The List::Utils may also have a method for strings

#!/usr/bin/perl use strict; use warnings; my @strings = qw( QS DD DFD SD QS QS QS DD DFS); my %count; $count{ $_ }++ for @strings; my @sorted = (sort {$count{$a} cmp $count{$b}} keys %count); print pop @sorted, "\n";

I'm not really a human, but I play one on earth.
Old Perl Programmer Haiku ................... flash japh

Replies are listed 'Best First'.
Re^2: find maximum occuring element in a array
by jwkrahn (Abbot) on Sep 07, 2011 at 17:47 UTC
    my @sorted = (sort {$count{$a} cmp $count{$b}} keys %count);

    $count{$a} and $count{$b} contain numbers so that should be:

    my @sorted = sort {$count{$a} <=> $count{$b}} keys %count;

    And you could accomplish the same effect with just one loop:

    $ perl -le' my @strings = qw( QS DD DFD SD QS QS QS DD DFS ); my ( %count, @max ); for ( @strings ) { $count{ $_ }++; $max[ 0 ] < $count{ $_ } and @max = ( $count{ $_ }, $_ ); } print $max[ 1 ]; ' QS

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (4)
As of 2024-03-28 17:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found