1 #!/usr/bin/perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-234/#TASK2 3 # 4 # Task 2: Unequal Triplets 5 # ======================== 6 # 7 # You are given an array of positive integers. 8 # 9 # Write a script to find the number of triplets (i, j, k) that satisfies 10 # num[i] != num[j], num[j] != num[k] and num[k] != num[i]. 11 # 12 ## Example 1 13 ## 14 ## Input: @ints = (4, 4, 2, 4, 3) 15 ## Ouput: 3 16 ## 17 ## (0, 2, 4) because 4 != 2 != 3 18 ## (1, 2, 4) because 4 != 2 != 3 19 ## (2, 3, 4) because 2 != 4 != 3 20 # 21 ## Example 2 22 ## 23 ## Input: @ints = (1, 1, 1, 1, 1) 24 ## Ouput: 0 25 # 26 ## Example 3 27 ## 28 ## Input: @ints = (4, 7, 1, 10, 7, 4, 1, 1) 29 ## Output: 28 30 ## 31 ## triplets of 1, 4, 7 = 3x2×2 = 12 combinations 32 ## triplets of 1, 4, 10 = 3×2×1 = 6 combinations 33 ## triplets of 4, 7, 10 = 2×2×1 = 4 combinations 34 ## triplets of 1, 7, 10 = 3x2x1 = 6 combinations 35 # 36 ############################################################ 37 ## 38 ## discussion 39 ## 40 ############################################################ 41 # 42 # We just walk the array from left to right 3 times inside of 43 # the previous loop and count the instances in which all 3 44 # numbers differ from each other 45 46 use strict; 47 use warnings; 48 49 unequal_triplets(4, 4, 2, 4, 3); 50 unequal_triplets(1, 1, 1, 1, 1); 51 unequal_triplets(4, 7, 1, 10, 7, 4, 1, 1); 52 53 sub unequal_triplets { 54 my @ints = @_; 55 print "Input: (" . join(", ", @ints) . ")\n"; 56 my $result = 0; 57 foreach my $i (0..$#ints) { 58 foreach my $j ($i+1..$#ints) { 59 foreach my $k ($j+1..$#ints) { 60 if($ints[$i] != $ints[$j] && $ints[$j] != $ints[$k] && $ints[$i] != $ints[$k]) { 61 $result++; 62 } 63 } 64 } 65 } 66 print "Output: $result\n"; 67 } 68