Robbie Hatley's Perl Solutions to The Weekly Challenge #199
For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle, usually with two parts, cycling every Sunday. You can find it here:
This week (2023-01-08 through 2023-01-14) is weekly challenge #199.
I found both parts of this week's challenge quite easy.
Part 1 is "Good Pairs" of list indices, where a "Good Pair" is an ordered pair of indices ($i, $j) such that $i<$j and $array[$i] == $array[$j]. This is easily done with a pair of nested 3-part for loops, like so:
for (@arrays){
my @array = @{$_};
my @good;
for ( my $i = 0 ; $i ≤ $#array - 1 ; ++$i ){
for ( my $j = $i + 1 ; $j ≤ $#array - 0 ; ++$j ){
if ( $array[$i] == $array[$j] ){
push @good, [$i, $j];}}}
my $good_count = scalar(@good);
say '';
say "list = (@array)";
say "Found $good_count \"Good Pairs\" of list indices:";
say "(@{$_})" for @good}
Part 2, "Good Triplets", is only slightly more elaborate. Given an array @array of integers and three integers $x, $y, $z, a "Good Triplet" is an ordered triplet of array values @array[$i, $j, $k] such that these 4 things are true:
a) 0 ≤ $i < $j < $k < (array size)
b) abs(array[$i] - array[$j]) ≤ x
c) abs(array[$j] - array[$k]) ≤ y
d) abs(array[$k] - array[$i]) ≤ z
My solution is exactly the same as for part 1: nested 3-part for loops, just 3 of them instead of 2:
for (@arrays){
my @array = @{$_};
my $z = pop @array;
my $y = pop @array;
my $x = pop @array;
my @good;
for ( my $i = 0 ; $i ≤ $#array - 2 ; ++$i ){
for ( my $j = $i + 1 ; $j ≤ $#array - 1 ; ++$j ){
for ( my $k = $j + 1 ; $k ≤ $#array - 0 ; ++$k ){
if ( abs($array[$i] - $array[$j]) ≤ $x
&& abs($array[$j] - $array[$k]) ≤ $y
&& abs($array[$k] - $array[$i]) ≤ $z){
push @good, [@array[$i, $j, $k]];}}}}
my $good_count = scalar(@good);
say '';
say "array = (@array)";
say "Found $good_count \"Good Triplets\" of array values:";
say "(@{$_})" for @good}
That's it for 199; looking forward to 200 this coming Sunday.
-- Cheers, Robbie Hatley
Comments
Post a Comment