diff options
| author | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2020-08-17 10:02:01 +0200 |
|---|---|---|
| committer | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2020-08-18 21:16:58 +0200 |
| commit | c30a1e8bf82756c8af444aeb0d29982ff8a08670 (patch) | |
| tree | 61f918691761e82fc5172f00ed937015d1a1202b | |
| parent | c81bbaaab14c1b99dcf68f5f9d1818e6295905a0 (diff) | |
| download | perlweeklychallenge-club-c30a1e8bf82756c8af444aeb0d29982ff8a08670.tar.gz perlweeklychallenge-club-c30a1e8bf82756c8af444aeb0d29982ff8a08670.tar.bz2 perlweeklychallenge-club-c30a1e8bf82756c8af444aeb0d29982ff8a08670.zip | |
solution to task 1
| -rwxr-xr-x | challenge-074/jo-37/perl/ch-1.pl | 24 |
1 files changed, 24 insertions, 0 deletions
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; |
