The weekly challenge 277 - Task 2: Strong Pair
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-277/#TASK2 3 # 4 # Task 2: Strong Pair 5 # =================== 6 # 7 # You are given an array of integers, @ints. 8 # 9 # Write a script to return the count of all strong pairs in the given array. 10 # 11 ### A pair of integers x and y is called strong pair if it satisfies: 12 ### 0 < |x - y| < min(x, y). 13 # 14 ## Example 1 15 ## 16 ## Input: @ints = (1, 2, 3, 4, 5) 17 ## Ouput: 4 18 ## 19 ## Strong Pairs: (2, 3), (3, 4), (3, 5), (4, 5) 20 # 21 ## Example 2 22 ## 23 ## Input: @ints = (5, 7, 1, 7) 24 ## Ouput: 1 25 ## 26 ## Strong Pairs: (5, 7) 27 # 28 ############################################################ 29 ## 30 ## discussion 31 ## 32 ############################################################ 33 # 34 # We just walk the array from beginning to end for x and from 35 # the current position to the end for y, then check if the two 36 # numbers at those positions satisfy the condition for being a 37 # strong pair. However, we only count the strong pair if it hasn't 38 # occured earlier, as can be seen in example 2 (the task itself 39 # is unclear about this). It is also unclear whether strong pairs 40 # (a, b) and (b, a) are considered the same; so in my solution I 41 # consider those the same. 42 # 43 44 use strict; 45 use warnings; 46 use List::Util qw(min max); 47 48 strong_pair(1, 2, 3, 4, 5); 49 strong_pair(5, 7, 1, 7); 50 51 sub strong_pair { 52 my @ints = @_; 53 print "Input: (", join(", ", @ints), ")\n"; 54 my $seen = {}; 55 my $output = 0; 56 foreach my $i (0..$#ints) { 57 foreach my $j ($i+1..$#ints) { 58 my $abs = abs($ints[$i] - $ints[$j]); 59 my $min = min($ints[$i], $ints[$j]); 60 my $max = max($ints[$i], $ints[$j]); 61 next if $seen->{$min}->{$max}; 62 next if $abs == 0; 63 next if $abs >= $min; 64 $seen->{$min}->{$max} = 1; 65 $output++; 66 } 67 } 68 print "Output: $output\n"; 69 }