diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2023-01-06 18:40:43 +0000 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-01-06 18:40:43 +0000 |
| commit | 3d9bfca5dfa4143b1d965e63328881fccb3bd2c5 (patch) | |
| tree | d934f2b8212bc19ea40a2b0c889b549be0991c7c | |
| parent | 9cce87b92d57d98ad3d543d6941d320f47759218 (diff) | |
| parent | 3463a7db59e4e326c595a10cfd9ec9836051a51e (diff) | |
| download | perlweeklychallenge-club-3d9bfca5dfa4143b1d965e63328881fccb3bd2c5.tar.gz perlweeklychallenge-club-3d9bfca5dfa4143b1d965e63328881fccb3bd2c5.tar.bz2 perlweeklychallenge-club-3d9bfca5dfa4143b1d965e63328881fccb3bd2c5.zip | |
Merge pull request #7366 from jo-37/contrib
Solutions to challenge 198
| -rwxr-xr-x | challenge-198/jo-37/perl/ch-1.pl | 67 | ||||
| -rwxr-xr-x | challenge-198/jo-37/perl/ch-2.sh | 5 |
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" |
