user2568702
user2568702

Reputation:

Find minium value that is maximum times in Array Perl

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.

Upvotes: 3

Views: 482

Answers (3)

Developer
Developer

Reputation: 6350

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";

Upvotes: 0

choroba
choroba

Reputation: 241968

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);

Upvotes: 3

mpapec
mpapec

Reputation: 50657

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";

Upvotes: 3

Related Questions