aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohammad Sajid Anwar <Mohammad.Anwar@yahoo.com>2024-08-30 20:34:03 +0100
committerGitHub <noreply@github.com>2024-08-30 20:34:03 +0100
commit2e7aed4897a5f26077b087713ee63b0daed17b31 (patch)
treea6961c83cae613b71fe5c6748077f6de615d2930
parent47a0f0b7eaae76317156768c5362512cc9ca26b3 (diff)
parente5f3073b67bf71736555ad7736d4dc07dc493725 (diff)
downloadperlweeklychallenge-club-2e7aed4897a5f26077b087713ee63b0daed17b31.tar.gz
perlweeklychallenge-club-2e7aed4897a5f26077b087713ee63b0daed17b31.tar.bz2
perlweeklychallenge-club-2e7aed4897a5f26077b087713ee63b0daed17b31.zip
Merge pull request #10731 from choroba/ech284
Add solutions to 284: Lucky Integer & Relative Sort by E. Choroba
-rwxr-xr-xchallenge-284/e-choroba/perl/ch-1.pl18
-rwxr-xr-xchallenge-284/e-choroba/perl/ch-2.pl35
2 files changed, 53 insertions, 0 deletions
diff --git a/challenge-284/e-choroba/perl/ch-1.pl b/challenge-284/e-choroba/perl/ch-1.pl
new file mode 100755
index 0000000000..9f165688c6
--- /dev/null
+++ b/challenge-284/e-choroba/perl/ch-1.pl
@@ -0,0 +1,18 @@
+#!/usr/bin/perl
+use warnings;
+use strict;
+use experimental qw( signatures );
+
+sub lucky_integer(@ints) {
+ my %freq;
+ ++$freq{$_} for @ints;
+ return (sort { $b <=> $a } -1, grep $_ == $freq{$_}, keys %freq)[0]
+}
+
+use Test::More tests => 3 + 1;
+
+is lucky_integer(2, 2, 3, 4), 2, 'Example 1';
+is lucky_integer(1, 2, 2, 3, 3, 3), 3, 'Example 2';
+is lucky_integer(1, 1, 1, 3), -1, 'Example 3';
+
+is lucky_integer(-2, 0), -1, 'Zero & negative';
diff --git a/challenge-284/e-choroba/perl/ch-2.pl b/challenge-284/e-choroba/perl/ch-2.pl
new file mode 100755
index 0000000000..15aaf904a9
--- /dev/null
+++ b/challenge-284/e-choroba/perl/ch-2.pl
@@ -0,0 +1,35 @@
+#!/usr/bin/perl
+use warnings;
+use strict;
+use experimental qw( signatures );
+
+sub relative_sort($list1, $list2) {
+ my %freq;
+ ++$freq{$_} for @$list1;
+
+ return [map(($_) x (delete $freq{$_} // 0), @$list2),
+ map +($_) x $freq{$_}, sort { $a <=> $b } keys %freq]
+}
+
+use Test2::V0;
+plan(3 + 1);
+
+is relative_sort([2, 3, 9, 3, 1, 4, 6, 7, 2, 8, 5],
+ [2, 1, 4, 3, 5, 6]),
+ [2, 2, 1, 4, 3, 3, 5, 6, 7, 8, 9],
+ 'Example 1';
+
+is relative_sort([3, 3, 4, 6, 2, 4, 2, 1, 3],
+ [1, 3, 2]),
+ [1, 3, 3, 3, 2, 2, 4, 4, 6],
+ 'Example 2';
+
+is relative_sort([3, 0, 5, 0, 2, 1, 4, 1, 1],
+ [1, 0, 3, 2]),
+ [1, 1, 1, 0, 0, 3, 2, 4, 5],
+ 'Example 3';
+
+is relative_sort([3, 2, 1],
+ [0, 1, 4, 2, 5, 3, 6]),
+ [1, 2, 3],
+ 'Shorter list, missing elements';