diff options
| author | Cris-HD <crisn7@hotmail.com> | 2020-08-22 17:51:50 +0200 |
|---|---|---|
| committer | Cris-HD <crisn7@hotmail.com> | 2020-08-22 17:51:50 +0200 |
| commit | 898477d6bf8b2b28fc641e954b3a84d14eae1935 (patch) | |
| tree | 399d7e4559fbb2c4279841d26f480b7f46e09282 /challenge-074 | |
| parent | 74729414de38358703031df835ee4e5bb25f9731 (diff) | |
| download | perlweeklychallenge-club-898477d6bf8b2b28fc641e954b3a84d14eae1935.tar.gz perlweeklychallenge-club-898477d6bf8b2b28fc641e954b3a84d14eae1935.tar.bz2 perlweeklychallenge-club-898477d6bf8b2b28fc641e954b3a84d14eae1935.zip | |
added ch-1.pl
Diffstat (limited to 'challenge-074')
| -rwxr-xr-x | challenge-074/cristian-heredia/perl/ch-1.pl | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/challenge-074/cristian-heredia/perl/ch-1.pl b/challenge-074/cristian-heredia/perl/ch-1.pl new file mode 100755 index 0000000000..db7be6f365 --- /dev/null +++ b/challenge-074/cristian-heredia/perl/ch-1.pl @@ -0,0 +1,48 @@ +#TASK #1 › Majority Element +#Submitted by: Mohammad S Anwar +#You are given an array of integers of size $N. + +#Write a script to find the majority element. If none found then print -1. + +#Majority element in the list is the one that appears more than floor(size_of_list/2). + +#Example 1 +#Input: @A = (1, 2, 2, 3, 2, 4, 2) +#Output: 2, as 2 appears 4 times in the list which is more than floor(7/2). + +#Example 2 +#Input: @A = (1, 3, 1, 2, 4, 5) +#Output: -1 as none of the elements appears more than floor(6/2). + + +use strict; +use warnings; +use Data::Dumper; +use List::Util qw(reduce); + +#Input +my @A = (1, 2, 2, 3, 2, 4, 2); + + +#Variables +my $floor = @A/2; + +my %count; +$count{$_}++ foreach @A; + +my $maxValue = List::Util::reduce { $count{$b} > $count{$a} ? $b : $a } keys %count; + +my $moreFrequest = $count{ $maxValue }; + +if ($moreFrequest > $floor) { + print "Output: $maxValue\n"; +} +else { + print "Output: -1\n"; +} + + + + + + |
