From 675064ba253fc10916663f7bd5d5d1e766cb83be Mon Sep 17 00:00:00 2001 From: Jörg Sommrey <28217714+jo-37@users.noreply.github.com> Date: Mon, 31 Oct 2022 16:25:27 +0100 Subject: Solution to task 1 --- challenge-189/jo-37/perl/ch-1.pl | 68 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100755 challenge-189/jo-37/perl/ch-1.pl diff --git a/challenge-189/jo-37/perl/ch-1.pl b/challenge-189/jo-37/perl/ch-1.pl new file mode 100755 index 0000000000..1a6bf09e20 --- /dev/null +++ b/challenge-189/jo-37/perl/ch-1.pl @@ -0,0 +1,68 @@ +#!/usr/bin/perl -s + +use v5.16; +use Test2::V0; +use List::Util 'reduce'; + +our ($tests, $examples, $target); + +run_tests() if $tests || $examples; # does not return + +die < Date: Mon, 31 Oct 2022 14:35:18 +0100 Subject: Solution to task 2 --- challenge-189/jo-37/perl/ch-2.pl | 92 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100755 challenge-189/jo-37/perl/ch-2.pl diff --git a/challenge-189/jo-37/perl/ch-2.pl b/challenge-189/jo-37/perl/ch-2.pl new file mode 100755 index 0000000000..5948418152 --- /dev/null +++ b/challenge-189/jo-37/perl/ch-2.pl @@ -0,0 +1,92 @@ +#!/usr/bin/perl -s + +use v5.16; +use Test2::V0; + +our ($tests, $examples); + +run_tests() if $tests || $examples; # does not return + +die < 0}; + while (my ($i, $n) = each @_) { + # Initialize $n's slot if necessary and create a shortcut. + my $s = $stats{$n} //= {}; + # Count occurrences and record the start position. + $s->{start} = $i unless $s->{cnt}++; + # Record the (current) end position. + $s->{end} = $i; + # Identify a new minimum candidate. + $min = $s if $s->{cnt} > $min->{cnt} || + $s->{cnt} == $min->{cnt} && + $s->{end} - $s->{start} < $min->{end} - $min->{start}; + } + + # Return the found minimum subarray. + @_[$min->{start} .. $min->{end}]; +} + + +### Examples and tests + +sub run_tests { + SKIP: { + skip "examples" unless $examples; + + is [min_subarr(1, 3, 3, 2)], [3, 3], 'Example 1'; + is [min_subarr(1, 2, 1, 3)], [1, 2, 1], 'Example 2'; + is [min_subarr(1, 3, 2, 1, 2)], [2, 1, 2], 'Example 3'; + is [min_subarr(1, 1, 2, 3, 2)], [1, 1], 'Example 4'; + is [min_subarr(2, 1, 2, 1, 1)], [1, 2, 1, 1], 'Example 5'; + } + + SKIP: { + skip "tests" unless $tests; + + is [min_subarr(1, 1, 1)], [1, 1, 1], 'Full array'; + is [min_subarr(1, 2, 3, 4, 5, 1)], [1, 2, 3, 4, 5, 1], 'Full array'; + is [min_subarr(1, 2, 3)], [1], 'Single element'; + } + + done_testing; + exit; +} -- cgit