1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-198/#TASK1
 3 #
 4 # You are given a list of integers, @list.
 5 #
 6 # Write a script to find the total pairs in the sorted list where 2 consecutive
 7 # elements has the max gap. If the list contains less then 2 elements then
 8 # return 0.
 9 #
10 ## Example 1
11 ##
12 ## Input:  @list = (2,5,8,1)
13 ## Output: 2
14 ##
15 ## Since the sorted list (1,2,5,8) has 2 such pairs (2,5) and (5,8)
16 #
17 ## Example 2
18 ##
19 ## Input: @list = (3)
20 ## Output: 0
21 #
22 ### This is a pretty straightforward problem. Let's just walk the array,
23 ### calculate the gap of 2 consecutive values, remember this instance, and in
24 ### the end display the value for the maximum of the gaps
25 
26 use strict;
27 use warnings;
28 use feature 'say';
29 use List::Util qw(max);
30 
31 # some examples of lists
32 my $lists = [
33    [ 2, 5, 8, 1 ],
34    [ 3 ],
35    [ 1, 2, 3, 5, 7, 9, 13, 17],
36    [ 1, 3, 7, 4, 9, 11 ]
37 ];
38 
39 # let's generate the output for all examples
40 foreach my $list ( @$lists ) {
41    say "(" . join(", ", @$list) . ") returns " . max_gap(@$list);
42 }
43 
44 # let's calculate the gaps
45 sub max_gap {
46    my @list = sort { $a <=> $b } @_;
47    my $gaps;
48    # if the list contains less than 2 elements then return 0
49    return 0 if scalar(@list) < 2;
50    my $last = undef;
51    foreach my $elem (@list) {
52       if(defined($last)) {
53          # we're at least at the second element, so let's calculate the gap
54          # to the previous element and count this instance
55          $gaps->{ $elem - $last }++;
56       }
57       $last = $elem;
58    }
59    # return the number of instances for the max gap
60    return $gaps->{ max(keys %$gaps) };
61 }
62