diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2020-03-12 07:48:53 +0000 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2020-03-12 07:48:53 +0000 |
| commit | 683758a6c871164b7fcd7519a411d17cd8e8f132 (patch) | |
| tree | a3213f718bf260d95d5383ada42b9565a6d32ffa /challenge-051 | |
| parent | d5e6f6dfce47d629c759e1cc60678966e49f9b35 (diff) | |
| parent | 7f6c8e2d49123c0599fce7a6ecb8f98fc578bf6c (diff) | |
| download | perlweeklychallenge-club-683758a6c871164b7fcd7519a411d17cd8e8f132.tar.gz perlweeklychallenge-club-683758a6c871164b7fcd7519a411d17cd8e8f132.tar.bz2 perlweeklychallenge-club-683758a6c871164b7fcd7519a411d17cd8e8f132.zip | |
Merge pull request #1398 from phillip-harris/branch-051
Challenge-051 solutions by phillip-harris
Diffstat (limited to 'challenge-051')
| -rw-r--r-- | challenge-051/phillip-harris/perl/ch-1.pl | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/challenge-051/phillip-harris/perl/ch-1.pl b/challenge-051/phillip-harris/perl/ch-1.pl new file mode 100644 index 0000000000..5a61dbc9ee --- /dev/null +++ b/challenge-051/phillip-harris/perl/ch-1.pl @@ -0,0 +1,51 @@ +#!/usr/env/perl +# Task 1 Challenge 051 Solution by phillip-harris +# 3 Sum +# Given an array @Lof integers. Write a script to find all unique +# triplets such that a + b + c is same as the given target T. Also +# make sure a <= b <= c. +# Here is wiki page for more information. +# Example: +# @L = (-25, -10, -7, -3, 2, 4, 8, 10); +# One such triplet for target 0 i.e. -10 + 2 + 8 = 0. + +# I read about the "two pointer trick" and decided to try to implement it +# instead of just brute forcing it. + +use strict; + +my @L = ( -25, -10, -7, -3, 2, 4, 8, 10 ); +my $target = 0; + +@L = sort { $a <=> $b } @L; + +print "INPUT:\n"; +print join ",", @L; +print "\n"; + +my %triplets; + +for ( my $x = 0 ; $x <= $#L ; $x++ ) { + my $start = $x + 1; + my $end = $#L; + my $current = $x; + + #print "\n$x\n"; + while ( ( $end - $start ) > 0 ) { + my $result = $L[$current] + $L[$start] + $L[$end]; + +#print "\n$current $start $end / $L[$current] + $L[$start] + $L[$end] = $result\n"; + if ( $result == $target ) { + + #print "triplet: $L[$current],$L[$start],$L[$end]\n"; + $triplets{"$L[$current],$L[$start],$L[$end]"} = 1; + $start++; + $end--; + } + elsif ( $result < $target ) { $start++ } + else { $end-- } + } +} + +print "\nOUTPUT:\n"; +print join "\n", keys(%triplets); |
