Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Finding maximum number of duplicates in an array

by rocketperl (Sexton)
on Jan 30, 2014 at 08:58 UTC ( #1072645=perlquestion: print w/ replies, xml ) Need Help??
rocketperl has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monkers, Is there a way to find the element that has maximum number of duplicates in an array? or should i loop to check for the maximum one? Thanks

Comment on Finding maximum number of duplicates in an array
Re: Finding maximum number of duplicates in an array
by Anonymous Monk on Jan 30, 2014 at 09:21 UTC

    Hi Monkers,

    Hello

    Is there a way to find the element that has maximum number of duplicates in an array?

    An element that has duplicates , in an array? Arrays are full of elements ... but what is an element that has duplicates? Duplicates of what?

    or should i loop to check for the maximum one? Thanks

    Yes, looping will be a part of any solution

Re: Finding maximum number of duplicates in an array
by vinoth.ree (Parson) on Jan 30, 2014 at 09:40 UTC

    Use hash and count the elements occurs in the array as follow.

    use strict; use warnings; use Data::Dumper; my %count; grep { ++$count{$_} } qw(a b a c d d e f g f h h); print Dumper \%count;
    Output
    $VAR1 = { 'e' => 1, 'a' => 2, 'd' => 2, 'c' => 1, 'h' => 2, 'b' => 1, 'g' => 1, 'f' => 2 };

    All is well
Re: Finding maximum number of duplicates in an array
by karlgoethebier (Priest) on Jan 30, 2014 at 09:42 UTC
Re: Finding maximum number of duplicates in an array
by johngg (Abbot) on Jan 30, 2014 at 13:26 UTC

    I'm not sure I've understood your requirement but is this what you meant?

    $ perl -Mstrict -Mwarnings -MList::Util=reduce -E ' > my @arr = qw{ a c b d b a b e f }; > my %dup; > push @{ $dup{ $arr[ $_ ] } }, $_ for 0 .. $#arr; > my $maxKey = > reduce { scalar @{ $dup{ $a } } > scalar @{ $dup{ $b } } ? $a : $ +b } > keys %dup; > say qq{Max dups for "$maxKey" at elements @{ $dup{ $maxKey } }};' Max dups for "b" at elements 2 4 6 $

    I hope I've guessed correctly and that this is helpful.

    Cheers,

    JohnGG

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1072645]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (6)
As of 2014-12-23 00:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (133 votes), past polls