aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorWalt Mankowski <waltman@pobox.com>2020-08-17 19:47:14 -0400
committerWalt Mankowski <waltman@pobox.com>2020-08-17 19:47:14 -0400
commite77f5b4c2fd92595000fb92dde051534a1ff299b (patch)
treed2fd8d8f700e5aeda23286154adff26c755c5597
parentced4cd787c08a9b9ab4f2b02aed12b0b4f572b86 (diff)
downloadperlweeklychallenge-club-e77f5b4c2fd92595000fb92dde051534a1ff299b.tar.gz
perlweeklychallenge-club-e77f5b4c2fd92595000fb92dde051534a1ff299b.tar.bz2
perlweeklychallenge-club-e77f5b4c2fd92595000fb92dde051534a1ff299b.zip
perl solution for challenge 74 task 1
-rw-r--r--challenge-074/walt-mankowski/perl/ch-1.pl36
1 files changed, 36 insertions, 0 deletions
diff --git a/challenge-074/walt-mankowski/perl/ch-1.pl b/challenge-074/walt-mankowski/perl/ch-1.pl
new file mode 100644
index 0000000000..3ad5aa7da7
--- /dev/null
+++ b/challenge-074/walt-mankowski/perl/ch-1.pl
@@ -0,0 +1,36 @@
+#!/usr/bin/env perl
+use strict;
+use warnings;
+use feature qw(:5.32);
+use experimental qw(signatures);
+
+# 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 = @ARGV;
+my $target = @a / 2;
+my $result = -1;
+my %cnt;
+
+for my $x (@a) {
+ if (++$cnt{$x} > $target) {
+ $result = $x;
+ last;
+ }
+}
+
+say $result;