P is for Practical PerlMonks

### Finding maximum number of duplicates in an array

by rocketperl (Sexton)
 on Jan 30, 2014 at 08:58 UTC 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

Replies are listed 'Best First'.
Re: Finding maximum number of duplicates in an array
by karlgoethebier (Prior) on Jan 30, 2014 at 09:42 UTC
Re: Finding maximum number of duplicates in an array
by vinoth.ree (Monsignor) 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 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

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

Create A New User
Node Status?
node history
Node Type: perlquestion [id://1072645]
Approved by Corion
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (13)
As of 2017-08-16 15:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Who is your favorite scientist and why?

Results (267 votes). Check out past polls.

Notices?