diff options
| author | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2023-04-12 21:29:51 +0200 |
|---|---|---|
| committer | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2023-04-19 18:48:49 +0200 |
| commit | e6f40eeff33a1cf61932aa1b9f5f6fc36db13226 (patch) | |
| tree | f6a0e2e24a39940c8e90ce6d0d007efd82857076 /challenge-051 | |
| parent | a63a88d296046ba8813f160737be12c6775f0e83 (diff) | |
| download | perlweeklychallenge-club-e6f40eeff33a1cf61932aa1b9f5f6fc36db13226.tar.gz perlweeklychallenge-club-e6f40eeff33a1cf61932aa1b9f5f6fc36db13226.tar.bz2 perlweeklychallenge-club-e6f40eeff33a1cf61932aa1b9f5f6fc36db13226.zip | |
Challenge 051 task 1
Diffstat (limited to 'challenge-051')
| -rwxr-xr-x | challenge-051/jo-37/perl/ch-1.pl | 78 |
1 files changed, 78 insertions, 0 deletions
diff --git a/challenge-051/jo-37/perl/ch-1.pl b/challenge-051/jo-37/perl/ch-1.pl new file mode 100755 index 0000000000..4937ce5d10 --- /dev/null +++ b/challenge-051/jo-37/perl/ch-1.pl @@ -0,0 +1,78 @@ +#!/usr/bin/perl -s + +use v5.24; +use Test2::V0; + +our ($tests, $examples); + +run_tests() if $tests || $examples; # does not return + +die <<EOS unless @ARGV > 3; +usage: $0 [-examples] [-tests] [TARGET N1 N2 N3...] + +-examples + run the examples from the challenge + +-tests + run some tests + +TARGET + target sum for three summands + +N1 N2 N3 + list of at least three numbers + +EOS + + +### Input and Output + +main: { + local $" = ','; + local $, = ','; + say map "(@$_)", three_sum(@ARGV)->@*; +} + + +### Implementation + +# Taken from https://en.wikipedia.org/wiki/3SUM#Quadratic_algorithm: +# Look up the required complement for each pair in a hash table. + +sub three_sum { + my $target = shift; + my @l = sort {$a <=> $b} @_; + + my %l; + @l{@l} = (); + my @res; + for my $p (0 .. $#l - 2) { + my $a = $l[$p]; + for my $q ($p + 1 .. $#l - 1) { + my $b = $l[$q]; + my $c = $target - $a - $b; + push @res, [$a, $b, $c] if $c >= $b && exists $l{$c} + } + } + \@res; +} + + +### Examples and tests + +sub run_tests { + SKIP: { + skip "examples" unless $examples; + + is three_sum(0, -25, -10, -7, -3, 2, 4, 8, 10), + bag {item [-10, 2, 8]; etc;}, 'example'; + + } + + SKIP: { + skip "tests" unless $tests; + } + + done_testing; + exit; +} |
