The weekly challenge 243 - Task 1: Reverse Pairs

 1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-243/#TASK1
 3 #
 4 # Task 1: Reverse Pairs
 5 # =====================
 6 #
 7 # You are given an array of integers.
 8 #
 9 # Write a script to return the number of reverse pairs in the given
10 # array.
11 #
12 # A reverse pair is a pair (i, j) where: a) 0 <= i < j < nums.length
13 # and b) nums[i] > 2 * nums[j].
14 #
15 ## Example 1
16 ##
17 ## Input: @nums = (1, 3, 2, 3, 1)
18 ## Output: 2
19 ##
20 ## (1, 4) => nums[1] = 3, nums[4] = 1, 3 > 2 * 1
21 ## (3, 4) => nums[3] = 3, nums[4] = 1, 3 > 2 * 1
22 #
23 ## Example 2
24 ##
25 ## Input: @nums = (2, 4, 3, 5, 1)
26 ## Output: 3
27 ##
28 ## (1, 4) => nums[1] = 4, nums[4] = 1, 4 > 2 * 1
29 ## (2, 4) => nums[2] = 3, nums[4] = 1, 3 > 2 * 1
30 ## (3, 4) => nums[3] = 5, nums[4] = 1, 5 > 2 * 1
31 #
32 ############################################################
33 ##
34 ## discussion
35 ##
36 ############################################################
37 #
38 # Walk the array twice (once from 0, once from the first index + 1)
39 # Check the condition in each case, counting the occurrences where
40 # the condition holds true.
41 
42 use strict;
43 use warnings;
44 
45 reverse_pairs(1, 3, 2, 3, 1);
46 reverse_pairs(2, 4, 3, 5, 1);
47 
48 sub reverse_pairs {
49    my @nums = @_;
50    my $result = 0;
51    print "Input: (" . join(", ", @nums) . ")\n";
52    foreach my $i (0..$#nums) {
53       foreach my $j ($i+1..$#nums) {
54          $result++ if $nums[$i] > 2 * $nums[$j];
55       }
56    }
57    print "Output: $result\n";
58 }