diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2023-01-10 18:38:48 +0000 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-01-10 18:38:48 +0000 |
| commit | 154a1b32caaec8a2ee85eba2f55d3475cd4867d7 (patch) | |
| tree | 08d0504bac54a1ad9592a20439a79557376acbb5 /challenge-199 | |
| parent | 43c5cd48a6369f58f1e40b310cf0a56b63c449aa (diff) | |
| parent | 2ea55eb9278c406022a1ac0123f3a9d78b65d120 (diff) | |
| download | perlweeklychallenge-club-154a1b32caaec8a2ee85eba2f55d3475cd4867d7.tar.gz perlweeklychallenge-club-154a1b32caaec8a2ee85eba2f55d3475cd4867d7.tar.bz2 perlweeklychallenge-club-154a1b32caaec8a2ee85eba2f55d3475cd4867d7.zip | |
Merge pull request #7394 from choroba/ech199
Add solutions to 199: Good Pairs & Good Triplets by E. Choroba
Diffstat (limited to 'challenge-199')
| -rwxr-xr-x | challenge-199/e-choroba/perl/ch-1.pl | 21 | ||||
| -rwxr-xr-x | challenge-199/e-choroba/perl/ch-2.pl | 28 |
2 files changed, 49 insertions, 0 deletions
diff --git a/challenge-199/e-choroba/perl/ch-1.pl b/challenge-199/e-choroba/perl/ch-1.pl new file mode 100755 index 0000000000..57a30da381 --- /dev/null +++ b/challenge-199/e-choroba/perl/ch-1.pl @@ -0,0 +1,21 @@ +#! /usr/bin/perl +use warnings; +use strict; +use experimental qw{ signatures }; + +use List::Util qw{ sum }; + +sub good_pairs ($list) { + my %counts; + ++$counts{$_} for @$list; + return sum(map $_ * ($_ - 1) / 2, values %counts) // 0 +} + +use Test::More tests => 3 + 2; + +is good_pairs([1, 2, 3, 1, 1, 3]), 4, 'Example 1'; +is good_pairs([1, 2, 3]), 0, 'Example 2'; +is good_pairs([1, 1, 1, 1]), 6, 'Example 3'; + +is good_pairs([1, 2, 1, 2, 1, 2, 1, 2, 1]), 16, '5+4'; +is good_pairs([]), 0, 'Empty'; diff --git a/challenge-199/e-choroba/perl/ch-2.pl b/challenge-199/e-choroba/perl/ch-2.pl new file mode 100755 index 0000000000..c59cba3414 --- /dev/null +++ b/challenge-199/e-choroba/perl/ch-2.pl @@ -0,0 +1,28 @@ +#! /usr/bin/perl +use warnings; +use strict; +use experimental 'signatures'; + +sub good_triplets ($arr, $x, $y, $z) { + # Optimization: abs can't be < 0. + return 0 if grep $_ < 0, $x, $y, $z; + + my $c = 0; + for my $i (0 .. $#$arr - 2) { + for my $j ($i + 1 .. $#$arr - 1) { + next unless abs($arr->[$i] - $arr->[$j]) <= $x; + for my $k ($j + 1 .. $#$arr) { + ++$c if abs($arr->[$j] - $arr->[$k]) <= $y + && abs($arr->[$i] - $arr->[$k]) <= $z; + } + } + } + return $c +} + +use Test::More tests => 2 + 1; + +is good_triplets([3, 0, 1, 1, 9, 7], 7, 2, 3), 4, 'Example 1'; +is good_triplets([1, 1, 2, 2, 3], 0, 0, 1), 0, 'Example 2'; + +is good_triplets([map int rand 100, 1 .. 1000], 0, 0, -1), 0, 'Negative'; |
