From 0911e211582f663efb0806b2c39a7d447765071a Mon Sep 17 00:00:00 2001 From: drbaggy Date: Tue, 29 Sep 2020 08:50:55 +0100 Subject: rewrite with a left to right and a right to left pass - this doesn't need the outer loop --- challenge-080/james-smith/perl/ch-2.pl | 27 +++++++++++++-------------- 1 file 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; } -- cgit