diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2022-04-20 09:24:24 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-04-20 09:24:24 +0100 |
| commit | 8bc50a9ba8ab63a721cccb7dec77f2a65202b2b4 (patch) | |
| tree | 623b849836133156f50d33fa4fd9807a5fedf306 /challenge-160 | |
| parent | 5d623604c821f6668c2a7f539a36122ec0e56774 (diff) | |
| parent | abc8adfa5a845e212623b4b0e122d0be267702c8 (diff) | |
| download | perlweeklychallenge-club-8bc50a9ba8ab63a721cccb7dec77f2a65202b2b4.tar.gz perlweeklychallenge-club-8bc50a9ba8ab63a721cccb7dec77f2a65202b2b4.tar.bz2 perlweeklychallenge-club-8bc50a9ba8ab63a721cccb7dec77f2a65202b2b4.zip | |
Merge pull request #5966 from drbaggy/master
Lots of stuff!
Diffstat (limited to 'challenge-160')
| -rw-r--r-- | challenge-160/james-smith/perl/ch-2.pl | 30 |
1 files changed, 26 insertions, 4 deletions
diff --git a/challenge-160/james-smith/perl/ch-2.pl b/challenge-160/james-smith/perl/ch-2.pl index 317e6031c9..184854564e 100644 --- a/challenge-160/james-smith/perl/ch-2.pl +++ b/challenge-160/james-smith/perl/ch-2.pl @@ -6,22 +6,44 @@ use warnings; use feature qw(say); use Test::More; -my @TESTS = ( +my @TESTS_POS = ( [ [1,3,5,7,9], 3 ], [ [1,2,3,4,5], -1 ], [ [2,4,2], 1 ], - [ [1,-1,1], 0 ], ## Not sure if -ve values allowed? + [ [1..51,1275],50 ], +); +my @TESTS = ( + @TESTS_POS, + [ [1,-1,1], 0 ], ## Not sure if -ve values allowed? + [ [-2,4,-2,1], 3 ], ); -is( equilibrium_index(@{$_->[0]}), $_->[1] ) foreach @TESTS; +is( equilibrium_index( @{$_->[0]}), $_->[1] ) foreach @TESTS; +is( equilibrium_index_positive(@{$_->[0]}), $_->[1] ) foreach @TESTS_POS; done_testing(); +## This doesn't assume anything about sign of values; +## +## There is a possible optimization if you only allow +## positive values that you can return -1 if $s<$_[$_] +## as once you have passed the balance point you can +## stop. + sub equilibrium_index { my $s = 0; $s += $_ for @_; - ($s==$_[$_]) ? (return $_) : ($s-=2*$_[$_]) for 0..$#_; + $s==$_[$_] ? (return $_) : ($s-=2*$_[$_]) for 0..$#_; + -1; +} + +## Optimized solution for +ve values only.... + +sub equilibrium_index_positive { + my $s = 0; + $s += $_ for @_; + $s==$_[$_] ? (return $_) : $s<$_[$_] ? (return -1) : ($s-=2*$_[$_]) for 0..$#_; -1; } |
