diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2022-04-11 18:30:49 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-04-11 18:30:49 +0100 |
| commit | 6e00dfa6b8f41f396a170bfc6f7729f94c80c38b (patch) | |
| tree | 0b2e2f8643ef900c2163da8e0e873f909554059a | |
| parent | fdd50e7ab4813e9bcd7fbe7ff825e34f32fe25c2 (diff) | |
| parent | 4454a107cc1abfc7bb45c239515cc4092ca7fbe3 (diff) | |
| download | perlweeklychallenge-club-6e00dfa6b8f41f396a170bfc6f7729f94c80c38b.tar.gz perlweeklychallenge-club-6e00dfa6b8f41f396a170bfc6f7729f94c80c38b.tar.bz2 perlweeklychallenge-club-6e00dfa6b8f41f396a170bfc6f7729f94c80c38b.zip | |
Merge pull request #5920 from choroba/ech160
Solve 160: Four Is Magic & Equilibrium Index by E. Choroba
| -rwxr-xr-x | challenge-160/e-choroba/perl/ch-1.pl | 27 | ||||
| -rwxr-xr-x | challenge-160/e-choroba/perl/ch-2.pl | 31 |
2 files changed, 58 insertions, 0 deletions
diff --git a/challenge-160/e-choroba/perl/ch-1.pl b/challenge-160/e-choroba/perl/ch-1.pl new file mode 100755 index 0000000000..5aa336efb2 --- /dev/null +++ b/challenge-160/e-choroba/perl/ch-1.pl @@ -0,0 +1,27 @@ +#!/usr/bin/perl +use warnings; +use strict; +use experimental 'signatures'; + +my @cardinals = qw( one two three four five six seven eight nine ); + +sub four_is_magic ($n) { + ucfirst _four_is_magic($n) . '.' +} + +sub _four_is_magic ($n) { + return 'four is magic' if 4 == $n; + + my $word = $cardinals[ $n - 1 ]; + my $length = length $word; + return "$word is $cardinals[ $length - 1 ], " . _four_is_magic($length) +} + +use Test::More tests => 3; + +is four_is_magic(5), + 'Five is four, four is magic.', 'Example 1'; +is four_is_magic(7), + 'Seven is five, five is four, four is magic.', 'Example 2'; +is four_is_magic(6), + 'Six is three, three is five, five is four, four is magic.', 'Example 3'; diff --git a/challenge-160/e-choroba/perl/ch-2.pl b/challenge-160/e-choroba/perl/ch-2.pl new file mode 100755 index 0000000000..195d7f286e --- /dev/null +++ b/challenge-160/e-choroba/perl/ch-2.pl @@ -0,0 +1,31 @@ +#!/usr/bin/perl +use warnings; +use strict; +use experimental 'signatures'; + +use List::Util qw{ sum }; + + +sub equilibrium_index ($array) { + my $i = 0; + my @sums = (0, sum(@$array) - $array->[0]); + my @results; + for my $i (1 .. $#$array - 1) { + $sums[0] += $array->[$i - 1]; + $sums[1] -= $array->[$i]; + push @results, $i if $sums[0] == $sums[1]; + } + + return @results if @results; + + return -1 +} + +use Test::More tests => 5; + +is_deeply [equilibrium_index([1, 3, 5, 7, 9])], [ 3], 'Example 1'; +is_deeply [equilibrium_index([1, 2, 3, 4, 5])], [-1], 'Example 2'; +is_deeply [equilibrium_index([2, 4, 2]) ], [ 1], 'Example 3'; + +is_deeply [equilibrium_index([1, 1, 1, -3, 7, 0])], [4], 'Negative numbers'; +is_deeply [equilibrium_index([0, 0, 0, 0])], [1, 2], 'More options'; |
