diff options
| author | Bob Lied <boblied+github@gmail.com> | 2023-11-02 19:00:44 -0500 |
|---|---|---|
| committer | Bob Lied <boblied+github@gmail.com> | 2023-11-02 19:00:44 -0500 |
| commit | a01357c96a9bc6f4425e77a5254419e4f603a7b9 (patch) | |
| tree | 49a9dea56ee19f6b6c07a4d07be07820a1582d49 | |
| parent | 29f7e5df704c38565548f328b4b2142450260ad8 (diff) | |
| download | perlweeklychallenge-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.pl | 11 |
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; |
