diff options
| author | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2022-12-21 11:14:32 +0100 |
|---|---|---|
| committer | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2022-12-23 15:14:40 +0100 |
| commit | dc40118e6ed9cc601daddf53dfa25ceb233a38ed (patch) | |
| tree | 6b7900a184b18dba90359ec6f31bdcde89455f38 /challenge-196/jo-37 | |
| parent | b7245409fff54180de5a95c80c8b5476119993e1 (diff) | |
| download | perlweeklychallenge-club-dc40118e6ed9cc601daddf53dfa25ceb233a38ed.tar.gz perlweeklychallenge-club-dc40118e6ed9cc601daddf53dfa25ceb233a38ed.tar.bz2 perlweeklychallenge-club-dc40118e6ed9cc601daddf53dfa25ceb233a38ed.zip | |
Solution to task 2
Diffstat (limited to 'challenge-196/jo-37')
| -rwxr-xr-x | challenge-196/jo-37/perl/ch-2.pl | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/challenge-196/jo-37/perl/ch-2.pl b/challenge-196/jo-37/perl/ch-2.pl new file mode 100755 index 0000000000..6019c07fac --- /dev/null +++ b/challenge-196/jo-37/perl/ch-2.pl @@ -0,0 +1,68 @@ +#!/usr/bin/perl -s + +use v5.16; +use Test2::V0; + +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 number to be searched for contiguous intervals. + +EOS + + +### Input and Output + +main: { + local $, = ', '; + local $" = ', '; + say map "[@$_]", range_list(@ARGV); +} + +### Implementation + +sub range_list { + # Collect contiguous intervals: + my @int = (['-inf']); + + # If the current number is the successor of the current interval's + # last seen element, take it as the new interval endpoint. Start a + # new interval otherwise. + $_ == $int[-1][-1] + 1 ? $int[-1][1] = $_ : push @int, [$_] for @_; + + # Discard point-only intervals. + grep @$_ > 1, @int; +} + + +### Examples and tests + +sub run_tests { + SKIP: { + skip "examples" unless $examples; + + is [range_list(1, 3, 4, 5, 7)], [[3, 5]], 'example 1'; + is [range_list(1, 2, 3, 6, 7, 9)], [[1, 3], [6, 7]], 'example 2'; + is [range_list(0, 1, 2, 4, 5, 6, 8, 9)], [[0, 2], [4, 6], [8, 9]], + 'example 3'; + } + + SKIP: { + skip "tests" unless $tests; + is [range_list(0, 2, 4, 6, 8)], [], 'none'; + } + + done_testing; + exit; +} |
