diff options
| author | KjetilS <kjetilskotheim@gmail.com> | 2025-02-18 18:55:09 +0100 |
|---|---|---|
| committer | KjetilS <kjetilskotheim@gmail.com> | 2025-02-18 18:55:09 +0100 |
| commit | b5f6dc2439462e261996363bee95c9958aa9bbe3 (patch) | |
| tree | 73693bd35082ab3940a34a4139b0187ff88ef80b /challenge-306 | |
| parent | 368d52f225fb9f9557fefee9cdd4db3825130ff1 (diff) | |
| download | perlweeklychallenge-club-b5f6dc2439462e261996363bee95c9958aa9bbe3.tar.gz perlweeklychallenge-club-b5f6dc2439462e261996363bee95c9958aa9bbe3.tar.bz2 perlweeklychallenge-club-b5f6dc2439462e261996363bee95c9958aa9bbe3.zip | |
https://theweeklychallenge.org/blog/perl-weekly-challenge-306/
Diffstat (limited to 'challenge-306')
| -rw-r--r-- | challenge-306/kjetillll/perl/ch-1.pl | 17 | ||||
| -rw-r--r-- | challenge-306/kjetillll/perl/ch-2.pl | 18 |
2 files changed, 35 insertions, 0 deletions
diff --git a/challenge-306/kjetillll/perl/ch-1.pl b/challenge-306/kjetillll/perl/ch-1.pl new file mode 100644 index 0000000000..397d5f41fb --- /dev/null +++ b/challenge-306/kjetillll/perl/ch-1.pl @@ -0,0 +1,17 @@ +#https://theweeklychallenge.org/blog/perl-weekly-challenge-306/ + +sub sos { #sum odd subarrays + eval join '+', #sum + map { + my $len = $_; + map @_[ $_ .. $_+$len-1 ], 0 .. @_ - $len #elems in all subarrays of length $len + } + grep $_ % 2, #only odd lengths + 1 .. @_; #sub array lengths +} + +use Test::More tests => 2; +is sos( @{ $$_{input} } ), $$_{output} for +{input => [2,5,3,6,4], output => 77}, +{input => [1,3], output => 4} + diff --git a/challenge-306/kjetillll/perl/ch-2.pl b/challenge-306/kjetillll/perl/ch-2.pl new file mode 100644 index 0000000000..96b046215f --- /dev/null +++ b/challenge-306/kjetillll/perl/ch-2.pl @@ -0,0 +1,18 @@ +#https://theweeklychallenge.org/blog/perl-weekly-challenge-306/ + +sub last_elem { + my($y, $x, @rest) = sort { $b <=> $a } @_; + ! @_ ? 0 + : @_==1 ? @_ + : last_elem( @rest, $x == $y ? () : $y - $x ) +} + +use Test::More tests => 2; +is last_elem(@{ $$_{input} }), $$_{output} for +{ input => [3, 8, 5, 2, 9, 2], output => 1 }, +{ input => [3, 2, 5], output => 0 }, + +__END__ +Todo: speedup / algorithm improvement for large lists: +sort list only once and use List::BinarySearch::XS::binsearch_pos() to +find the insert positions for y-x when y != x, insert with splice() |
