aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohammad S Anwar <Mohammad.Anwar@yahoo.com>2020-08-17 20:08:19 +0100
committerGitHub <noreply@github.com>2020-08-17 20:08:19 +0100
commitf3ade4e9cd0afe3a369e331cc571fef370c925ae (patch)
treeae2e6d0696647dadb5b5bbdf92c5383fb6e38164
parent5d14813628dfc045183d407a2307d0697fb54633 (diff)
parent369e3fb38abf3ee3e2dbde3ad919591d6004a390 (diff)
downloadperlweeklychallenge-club-f3ade4e9cd0afe3a369e331cc571fef370c925ae.tar.gz
perlweeklychallenge-club-f3ade4e9cd0afe3a369e331cc571fef370c925ae.tar.bz2
perlweeklychallenge-club-f3ade4e9cd0afe3a369e331cc571fef370c925ae.zip
Merge pull request #2095 from poizon/branch-for-challenge-074
Add solution for Task-1 at Ch-074
-rw-r--r--challenge-074/pavel_kuptsov/perl/ch-1.pl39
1 files changed, 39 insertions, 0 deletions
diff --git a/challenge-074/pavel_kuptsov/perl/ch-1.pl b/challenge-074/pavel_kuptsov/perl/ch-1.pl
new file mode 100644
index 0000000000..c9a66cb4a5
--- /dev/null
+++ b/challenge-074/pavel_kuptsov/perl/ch-1.pl
@@ -0,0 +1,39 @@
+#!/usr/bin/perl -w
+use strict;
+use warnings;
+use v5.26;
+use Test::More;
+use POSIX qw(floor);
+# 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).
+
+my @A = (1, 2, 2, 3, 2, 4, 2);
+my @B = (1, 3, 1, 2, 4, 5);
+
+sub majority_el
+{
+ my $arr_ref = shift;
+ my $o = {};
+ map { $o->{$_}++ } @$arr_ref;
+ my ($max) = sort { $o->{$b} <=> $o->{$a} } keys %$o;
+
+ return $o->{$max} >= floor(@$arr_ref/2) ? $max : -1;
+}
+
+ok(majority_el(\@A) == 2 );
+ok(majority_el(\@B) == -1);
+
+done_testing(2); \ No newline at end of file