The weekly challenge 241 - Task 1: Arithmetic Triplets

 1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-241/#TASK1
 3 #
 4 # Task 1: Arithmetic Triplets
 5 # ===========================
 6 #
 7 # You are given an array (3 or more members) of integers in increasing order
 8 # and a positive integer.
 9 #
10 # Write a script to find out the number of unique Arithmetic Triplets
11 # satisfying the following rules:
12 #
13 # a) i < j < k
14 # b) nums[j] - nums[i] == diff
15 # c) nums[k] - nums[j] == diff
16 #
17 ## Example 1
18 ##
19 ## Input: @nums = (0, 1, 4, 6, 7, 10)
20 ##        $diff = 3
21 ## Output: 2
22 ##
23 ## Index (1, 2, 4) is an arithmetic triplet because both  7 - 4 == 3 and 4 - 1 == 3.
24 ## Index (2, 4, 5) is an arithmetic triplet because both 10 - 7 == 3 and 7 - 4 == 3.
25 #
26 ## Example 2
27 ##
28 ## Input: @nums = (4, 5, 6, 7, 8, 9)
29 ##        $diff = 2
30 ## Output: 2
31 ##
32 ## (0, 2, 4) is an arithmetic triplet because both 8 - 6 == 2 and 6 - 4 == 2.
33 ## (1, 3, 5) is an arithmetic triplet because both 9 - 7 == 2 and 7 - 5 == 2.
34 #
35 ############################################################
36 ##
37 ## discussion
38 ##
39 ############################################################
40 #
41 # Looping over the indices i, j, k we just check the condition.
42 # We can even short-curcuit the inner loop because we only need
43 # to execute it if $nums[$j] - $nums[$i] == $diff.
44 
45 use strict;
46 use warnings;
47 
48 arithmetic_triplets( [0, 1, 4, 6, 7, 10], 3 );
49 arithmetic_triplets( [4, 5, 6, 7, 8, 9], 2);
50 
51 sub arithmetic_triplets {
52    my ($nums, $diff) = @_;
53    my @nums = @$nums;
54    my $result = 0;
55    print "Input: (" . join(", ", @nums) . "), $diff\n";
56    foreach my $i (0..$#nums) {
57       foreach my $j ($i+1..$#nums) {
58          if($nums[$j] - $nums[$i] == $diff) {
59             foreach my $k ($j+1..$#nums) {
60                if($nums[$k] - $nums[$j] == $diff) {
61                   $result++;
62                }
63             }
64          }
65       }
66    }
67    print "Output: $result\n";
68 }
69