From 898477d6bf8b2b28fc641e954b3a84d14eae1935 Mon Sep 17 00:00:00 2001 From: Cris-HD Date: Sat, 22 Aug 2020 17:51:50 +0200 Subject: added ch-1.pl --- challenge-074/cristian-heredia/perl/ch-1.pl | 48 +++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100755 challenge-074/cristian-heredia/perl/ch-1.pl 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"; +} + + + + + + -- cgit