From c30a1e8bf82756c8af444aeb0d29982ff8a08670 Mon Sep 17 00:00:00 2001 From: Jörg Sommrey <28217714+jo-37@users.noreply.github.com> Date: Mon, 17 Aug 2020 10:02:01 +0200 Subject: solution to task 1 --- challenge-074/jo-37/perl/ch-1.pl | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100755 challenge-074/jo-37/perl/ch-1.pl diff --git a/challenge-074/jo-37/perl/ch-1.pl b/challenge-074/jo-37/perl/ch-1.pl new file mode 100755 index 0000000000..6e95824317 --- /dev/null +++ b/challenge-074/jo-37/perl/ch-1.pl @@ -0,0 +1,24 @@ +#!/usr/bin/perl + +use v5.16; +use Test2::V0; +use warnings FATAL => 'all'; + +use List::MoreUtils qw(frequency); +use List::Util qw(pairfirst); +use Math::Utils qw(floor); + +sub majority_element { + + # As there can be at most one element with a frequency + # above floor(size_of_list / 2), only the first matching + # value/frequency-pair may have the result. + (pairfirst {$b > floor(@_ / 2)} frequency @_)[0] // -1; +} + +is majority_element(1, 2, 2, 3, 2, 4, 2), 2, 'first example'; +is majority_element(1, 3, 1, 2, 4, 5), -1, 'second example'; +is majority_element(1, 2, 2, 3, 2, 4, 2, 1), -1, 'even sized list'; +is majority_element(0, 1, 0, 1, 0), 0, 'zero majority'; + +done_testing; -- cgit