3

I have a requirement to find out the minimum value that is occurring maximum times in the array .I have store those values in other array .

my @arr=(1,2,3,4,1,3,4,1);

1 is the minimum value that is occurring maximum times.

3
  • How about my @arr=(1,2,2,2,1,2,2,1);? 1 is smaller while 2 occurs more times?
    – Yu Hao
    Sep 17, 2013 at 7:19
  • so 2 will be the output as i think
    – Developer
    Sep 17, 2013 at 7:20
  • yes @GauravPandey your right
    – user2568702
    Sep 17, 2013 at 7:22

3 Answers 3

3

If there are two or more elements occurring same number of times, smaller is preferred:

my @arr=(1,2,3,4,1,3,4,1);

my %seen;
$seen{$_}++ for @arr;

my ($min_val) = sort { $seen{$b} <=> $seen{$a} || $a <=> $b } keys %seen;
print "$min_val\n";
3

You can use a hash to count the occurrences of each number. The most frequent numbers can be found as having the frequence equal to the max of the frequences, the minimum among them can be found by min, both min and max come from List::Util.

#!/usr/bin/perl

use warnings;
use strict;

use List::Util qw(min max);

my @arr = (1, 2, 3, 4, 1, 3, 4, 1);
my %occurrences;
$occurrences{$_}++ for @arr;
my $max_freq = max(values %occurrences);
print min(grep $max_freq == $occurrences{$_}, keys %occurrences);
0

Use this it will work perfect for you

my @arr=(1, 2, 3, 4, 1, 3, 4, 1);
my %count;
foreach (@arr){
    $count{$_}++;
}
my ($min_by_value) = sort { $a <=> $b} keys %count;
my ($max_by_count) = sort { $count{$b} <=> $count{$a} } keys %count;
my $max =
    ($count{$min_by_value} >= $count{$max_by_count}) ? $min_by_value : $max_by_count;
print "minimum value max times = $max\n";
2
  • this is not working as if the all the values are same then it is working
    – user2568702
    Sep 17, 2013 at 7:24
  • @Rahul i have updated my answer i have checked this it's working fine
    – Developer
    Sep 17, 2013 at 7:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.