1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-199/#TASK2
 3 #
 4 # You are given an array of integers, @array and three integers $x,$y,$z.
 5 #
 6 # Write a script to find out total Good Triplets in the given array.
 7 # 
 8 # A triplet array[i], array[j], array[k] is good if it satisfies the following conditions:
 9 # 
10 ## a) 0 <= i < j < k <= n (size of given array)
11 ## b) abs(array[i] - array[j]) <= x
12 ## c) abs(array[j] - array[k]) <= y
13 ## d) abs(array[i] - array[k]) <= z
14 # 
15 #####################################
16 #
17 # solution:
18 #
19 # The solution to this problem is a bit similar to the first one where we have
20 # to walk the array with 2 variables; now we need three, and the check we have
21 # to do for each iteration is a bit more complicated.
22 #
23 
24 
25 use strict;
26 use warnings;
27 
28 # some examples
29 
30 my @examples = (
31    [[3,0,1,1,9,7], 7, 2, 3],
32    [[1,1,2,2,3],0,0,1]
33 );
34 
35 foreach my $example (@examples) {
36    my ($list, $x, $y, $z) = @$example;
37    find_good_triplets($x, $y, $z, @$list);
38 }
39 
40 sub find_good_triplets {
41    my ($x, $y, $z, @list) = @_;
42    my $count = 0;
43    foreach my $i (0..$#list) {
44       foreach my $j ($i+1..$#list) {
45          foreach my $k ($j+1..$#list) {
46             $count++ if abs($list[$i]-$list[$j]) <= $x and abs($list[$j]-$list[$k]) <= $y and abs($list[$i]-$list[$k]) <= $z;
47          }
48       }
49    }
50    print "[" . join(",",@list) . "] returns $count\n";
51 }
52