aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBob Lied <boblied+github@gmail.com>2023-11-02 19:00:44 -0500
committerBob Lied <boblied+github@gmail.com>2023-11-02 19:00:44 -0500
commita01357c96a9bc6f4425e77a5254419e4f603a7b9 (patch)
tree49a9dea56ee19f6b6c07a4d07be07820a1582d49
parent29f7e5df704c38565548f328b4b2142450260ad8 (diff)
downloadperlweeklychallenge-club-a01357c96a9bc6f4425e77a5254419e4f603a7b9.tar.gz
perlweeklychallenge-club-a01357c96a9bc6f4425e77a5254419e4f603a7b9.tar.bz2
perlweeklychallenge-club-a01357c96a9bc6f4425e77a5254419e4f603a7b9.zip
Optimization to end loop early once difference can't be achieved
-rw-r--r--challenge-241/bob-lied/perl/ch-1.pl11
1 files changed, 9 insertions, 2 deletions
diff --git a/challenge-241/bob-lied/perl/ch-1.pl b/challenge-241/bob-lied/perl/ch-1.pl
index 28954dc13b..efb05edce9 100644
--- a/challenge-241/bob-lied/perl/ch-1.pl
+++ b/challenge-241/bob-lied/perl/ch-1.pl
@@ -46,10 +46,17 @@ sub triplet($diff, @nums)
{
for ( my $j = $i+1; $j <= $#nums-1; $j++ )
{
- next unless $nums[$j] - $nums[$i] == $diff;
+ my $dj = $nums[$j] - $nums[$i];
+
+ # Input is sorted, so stop once the difference is too big.
+ last if $dj > $diff;
+ next unless $dj == $diff;
+
for ( my $k = $j+1; $k <= $#nums ; $k++ )
{
- if ( $nums[$k] - $nums[$j] == $diff )
+ my $dk = $nums[$k] - $nums[$j];
+ last if $dk > $diff;
+ if ( $dk == $diff )
{
$count++;
push @show, [ $i, $j, $k ] if $Verbose;