aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJörg Sommrey <28217714+jo-37@users.noreply.github.com>2023-01-06 14:28:49 +0100
committerJörg Sommrey <28217714+jo-37@users.noreply.github.com>2023-01-06 14:28:49 +0100
commit3463a7db59e4e326c595a10cfd9ec9836051a51e (patch)
tree0600fe3a6c9e46ef7561cf5988ac039fbfcaa4e6
parenta3955b58c74d643c9cbff8fe2b43e4befb1f32ba (diff)
parent4012ef282b2effc208bb550f301fbe0937f430e2 (diff)
downloadperlweeklychallenge-club-3463a7db59e4e326c595a10cfd9ec9836051a51e.tar.gz
perlweeklychallenge-club-3463a7db59e4e326c595a10cfd9ec9836051a51e.tar.bz2
perlweeklychallenge-club-3463a7db59e4e326c595a10cfd9ec9836051a51e.zip
Solutions to challenge 198
-rwxr-xr-xchallenge-198/jo-37/perl/ch-1.pl67
-rwxr-xr-xchallenge-198/jo-37/perl/ch-2.sh5
2 files changed, 72 insertions, 0 deletions
diff --git a/challenge-198/jo-37/perl/ch-1.pl b/challenge-198/jo-37/perl/ch-1.pl
new file mode 100755
index 0000000000..c406cbc810
--- /dev/null
+++ b/challenge-198/jo-37/perl/ch-1.pl
@@ -0,0 +1,67 @@
+#!/usr/bin/perl -s
+
+use v5.16;
+use Test2::V0 '!float';
+use PDL;
+
+our ($tests, $examples);
+
+run_tests() if $tests || $examples; # does not return
+
+die <<EOS unless @ARGV;
+usage: $0 [-examples] [-tests] [--] [N...]
+
+-examples
+ run the examples from the challenge
+
+-tests
+ run some tests
+
+N...
+ list of integers
+
+EOS
+
+
+### Input and Output
+
+say count_max_gap(@ARGV);
+
+
+### Implementation
+
+# Sort the numbers, build pairs of adjacent values, take the differences
+# of the pairs by flipping the sign of the second elements and summing
+# over the pairs. Then count the elements having the maximum value.
+sub count_max_gap {
+ return 0 unless @_ > 1;
+ my $gap = sumover long(@_)->qsort->lags(0, 1, 2)->xchg(0, 1) * long 1, -1;
+
+ $gap->where($gap == max $gap)->dim(0);
+}
+
+
+### Examples and tests
+
+sub run_tests {
+ SKIP: {
+ skip "examples" unless $examples;
+
+ is count_max_gap(qw(2 5 8 1)), 2, 'example 1';
+ is count_max_gap(3), 0, 'example 2';
+ }
+
+ SKIP: {
+ skip "tests" unless $tests;
+
+ is count_max_gap(qw(8 6 4 3 2 1)), 2, 'max count not at max gap';
+ is count_max_gap(qw(3 3 3)), 2, 'zero gap';
+ is count_max_gap(qw(5 3 2 1)), 1, 'single max gap';
+ is count_max_gap(qw(1 2 3 -1)), 1, 'negative number in max gap';
+ is count_max_gap(2, 1), 1, 'single gap';
+ is count_max_gap(), 0, 'empty list';
+ }
+
+ done_testing;
+ exit;
+}
diff --git a/challenge-198/jo-37/perl/ch-2.sh b/challenge-198/jo-37/perl/ch-2.sh
new file mode 100755
index 0000000000..14174f9d2b
--- /dev/null
+++ b/challenge-198/jo-37/perl/ch-2.sh
@@ -0,0 +1,5 @@
+#!/bin/sh
+
+# "prime_count" has inclusive ranges, so we need to adjust the limit.
+# This neat subtlety was carefully avoided in the examples.
+perl -MMath::Prime::Util=:all -E "say prime_count $1 - 1"