aboutsummaryrefslogtreecommitdiff
path: root/challenge-080/james-smith
diff options
context:
space:
mode:
authordrbaggy <js5@sanger.ac.uk>2020-09-29 08:50:55 +0100
committerdrbaggy <js5@sanger.ac.uk>2020-09-29 08:50:55 +0100
commit0911e211582f663efb0806b2c39a7d447765071a (patch)
tree8950fb373261ff979a81f0e2575b95cf3e1b3fd1 /challenge-080/james-smith
parent3d582d8fd55cef900675a2aa5885d18ab7b8ed82 (diff)
downloadperlweeklychallenge-club-0911e211582f663efb0806b2c39a7d447765071a.tar.gz
perlweeklychallenge-club-0911e211582f663efb0806b2c39a7d447765071a.tar.bz2
perlweeklychallenge-club-0911e211582f663efb0806b2c39a7d447765071a.zip
rewrite with a left to right and a right to left pass - this doesn't need the outer loop
Diffstat (limited to 'challenge-080/james-smith')
-rw-r--r--challenge-080/james-smith/perl/ch-2.pl27
1 files changed, 13 insertions, 14 deletions
diff --git a/challenge-080/james-smith/perl/ch-2.pl b/challenge-080/james-smith/perl/ch-2.pl
index a8eacfb22e..c263204651 100644
--- a/challenge-080/james-smith/perl/ch-2.pl
+++ b/challenge-080/james-smith/perl/ch-2.pl
@@ -10,6 +10,7 @@ use Test::More;
is( candies( qw(1 2 2) ), 4 );
is( candies( qw(1 4 3 2) ), 7 );
is( candies( qw(5 4 3 2 1) ), 15 );
+is( candies( qw(5 4 3 4 3 2 1) ), 16 );
is( candies( qw(2 1 2 1 2 1 2) ), 11 );
done_testing;
@@ -18,18 +19,16 @@ sub candies {
my @ranks = @_;
my $prev_count = my @candies = map { 1 } @ranks; ## First pass we set everything to 1!
my $flag;
- do {
- my $count = 0;
- foreach( 0..(@ranks-2) ) { ## Loop through comparing element to next one - increase as approprite
- $candies[$_+1] = $candies[$_ ]+1 if $ranks[$_] < $ranks[$_+1] && $candies[$_] >= $candies[$_+1];
- $candies[$_] = $candies[$_+1]+1 if $ranks[$_] > $ranks[$_+1] && $candies[$_] <= $candies[$_+1];
- $count += $candies[$_ ]; ## by the time we get here we would have done both comparisons that
- ## cause this entry to be updated..
- }
-
- $count += $candies[-1]; ## Add count for the last element...
-
- return $count if $count == $prev_count; ## Totals are the same so nothing been update can return
- $prev_count = $count;
- } while( 1 ); ## Infinite loop - will hit exit condition in loop...!
+ ## Sweep left first...
+ foreach( 0..(@ranks-2) ) {
+ $candies[$_+1] = $candies[$_]+1 if $ranks[$_] < $ranks[$_+1] && $candies[$_] >= $candies[$_+1];
+ }
+ ## Then sweep right... we have to go right to left otherwise you don't get the right answer
+ ## at the end...
+ foreach( reverse 1..(@ranks-1) ) {
+ $candies[$_-1] = $candies[$_]+1 if $ranks[$_] < $ranks[$_-1] && $candies[$_] >= $candies[$_-1];
+ }
+ my $t = 0;
+ $t+= $_ foreach @candies;
+ return $t;
}