diff options
| author | Mohammad Sajid Anwar <Mohammad.Anwar@yahoo.com> | 2023-07-12 10:06:42 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-07-12 10:06:42 +0100 |
| commit | 88767aa7b424c4abea63df17ce4c896e2c3562bb (patch) | |
| tree | a05c15b69a560b8239a405a264f2bff90c6946aa | |
| parent | 9c9a21b09e905457b595efda305e66b2a518a8b0 (diff) | |
| parent | e4768d30224284b0cb88372ae0c2de42e2242344 (diff) | |
| download | perlweeklychallenge-club-88767aa7b424c4abea63df17ce4c896e2c3562bb.tar.gz perlweeklychallenge-club-88767aa7b424c4abea63df17ce4c896e2c3562bb.tar.bz2 perlweeklychallenge-club-88767aa7b424c4abea63df17ce4c896e2c3562bb.zip | |
Merge pull request #8359 from choroba/ech225
Add solutions to 225: Max Words & Left Right Sum Diff by E. Choroba
| -rwxr-xr-x | challenge-225/e-choroba/perl/ch-1.pl | 22 | ||||
| -rwxr-xr-x | challenge-225/e-choroba/perl/ch-2.pl | 49 |
2 files changed, 71 insertions, 0 deletions
diff --git a/challenge-225/e-choroba/perl/ch-1.pl b/challenge-225/e-choroba/perl/ch-1.pl new file mode 100755 index 0000000000..374bdc110e --- /dev/null +++ b/challenge-225/e-choroba/perl/ch-1.pl @@ -0,0 +1,22 @@ +#!/usr/bin/perl +use warnings; +use strict; +use experimental qw( signatures ); + +use List::Util qw{ max }; + +sub max_words(@list) { + return max(map { my $c = () = /\w+/g } @list) +} + +use Test::More tests => 2; + +is max_words("Perl and Raku belong to the same family.", + "I love Perl.", + "The Perl and Raku Conference."), + 8, 'Example 1'; + +is max_words("The Weekly Challenge.", + "Python is the most popular guest language.", + "Team PWC has over 300 members."), + 7, 'Example 2'; diff --git a/challenge-225/e-choroba/perl/ch-2.pl b/challenge-225/e-choroba/perl/ch-2.pl new file mode 100755 index 0000000000..c41149d052 --- /dev/null +++ b/challenge-225/e-choroba/perl/ch-2.pl @@ -0,0 +1,49 @@ +#!/usr/bin/perl +use warnings; +use strict; +use experimental qw( signatures ); + +use List::Util qw{ sum0 }; + +sub left_right_sum_diff(@ints) { + my $l = 0; + my $r = sum0(@ints[1 .. $#ints]); + my @diff; + for my $i (0 .. $#ints) { + push @diff, abs($l - $r); + $l += $ints[$i]; + $r -= $i < $#ints ? $ints[$i + 1] : 0; + } + return \@diff +} + +sub left_right_sum_diff_naive(@ints) { + my @left = my $s = 0; + push @left, map $s += $_, @ints[0 .. $#ints - 1]; + + $s = 0; + my @right = reverse 0, map $s += $_, reverse @ints[1 .. $#ints]; + + return [map abs($left[$_] - $right[$_]), 0 .. $#left] +} + +use Test2::V0; +plan 2 * 3; + +for my $f (*left_right_sum_diff_naive{CODE}, *left_right_sum_diff{CODE}) { + is $f->(10, 4, 8, 3), [15, 1, 11, 22], 'Example 1'; + is $f->(1), [0], 'Example 2'; + is $f->(1, 2, 3, 4, 5), [14, 11, 6, 1, 10], 'Example 3'; +} + +use Benchmark qw{ cmpthese }; +my @in = 1 .. 15; +cmpthese(-3, { + naive => sub { left_right_sum_diff_naive(@in) }, + optimized => sub { left_right_sum_diff(@in) }, +}); + +__END__ + Rate naive optimized +naive 133552/s -- -20% +optimized 167637/s 26% -- |
