The weekly challenge 262: Task 2: Count Equal Divisible
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-262/#TASK2 3 # 4 # Task 2: Count Equal Divisible 5 # ============================= 6 # 7 # You are given an array of integers, @ints and an integer $k. 8 # 9 # Write a script to return the number of pairs (i, j) where 10 # 11 # a) 0 <= i < j < size of @ints 12 # b) ints[i] == ints[j] 13 # c) i x j is divisible by k 14 # 15 ## Example 1 16 ## 17 ## Input: @ints = (3,1,2,2,2,1,3) and $k = 2 18 ## Output: 4 19 ## 20 ## (0, 6) => ints[0] == ints[6] and 0 x 6 is divisible by 2 21 ## (2, 3) => ints[2] == ints[3] and 2 x 3 is divisible by 2 22 ## (2, 4) => ints[2] == ints[4] and 2 x 4 is divisible by 2 23 ## (3, 4) => ints[3] == ints[4] and 3 x 4 is divisible by 2 24 # 25 ## Example 2 26 ## 27 ## Input: @ints = (1,2,3) and $k = 1 28 ## Output: 0 29 # 30 ############################################################ 31 ## 32 ## discussion 33 ## 34 ############################################################ 35 # 36 # Have one index variable go from 0 to size of @ints - 1, then 37 # another walk from the first index + 1 to size of @ints - 1. In 38 # case ints[i] == ints[j], check if the product of i and j is 39 # divisible by $k. Return the sum of all instances where this is true. 40 41 use strict; 42 use warnings; 43 44 count_equal_divisible( [3,1,2,2,2,1,3], 2); 45 count_equal_divisible( [1,2,3], 1); 46 47 sub count_equal_divisible { 48 my ($tmp, $k) = @_; 49 my @ints = @$tmp; 50 print "Input: (" . join(", ", @ints) . ")\n"; 51 my $result = 0; 52 foreach my $i (0 .. $#ints) { 53 foreach my $j ($i+1 .. $#ints) { 54 if($ints[$i] == $ints[$j]) { 55 $result++ unless $i * $j % $k; 56 } 57 } 58 } 59 print "Output: $result\n"; 60 }