perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 309 - Task 1: Min Gap

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-309/#TASK1
 3 #
 4 # Task 1: Min Gap
 5 # ===============
 6 #
 7 # You are given an array of integers, @ints, increasing order.
 8 #
 9 # Write a script to return the element before which you find the smallest gap.
10 #
11 ## Example 1
12 ##
13 ## Input: @ints = (2, 8, 10, 11, 15)
14 ## Output: 11
15 ##
16 ##  8 - 2  => 6
17 ## 10 - 8  => 2
18 ## 11 - 10 => 1
19 ## 15 - 11 => 4
20 ##
21 ## 11 is where we found the min gap.
22 #
23 ## Example 2
24 ##
25 ## Input: @ints = (1, 5, 6, 7, 14)
26 ## Output: 6
27 ##
28 ##  5 - 1 => 4
29 ##  6 - 5 => 1
30 ##  7 - 6 => 1
31 ## 14 - 7 => 7
32 ##
33 ## 6 and 7 where we found the min gap, so we pick the first instance.
34 #
35 ## Example 3
36 ##
37 ## Input: @ints = (8, 20, 25, 28)
38 ## Output: 28
39 ##
40 ##  8 - 20 => 14
41 ## 25 - 20 => 5
42 ## 28 - 25 => 3
43 ##
44 ## 28 is where we found the min gap.
45 #
46 ############################################################
47 ##
48 ## discussion
49 ##
50 ############################################################
51 #
52 # This one is straight forward: Walk the array from left to right.
53 # Whenever we find a smaller gap, we keep track of the new min gap
54 # and the element at that position. We can then return the remembered
55 # element in the end.
56 
57 use v5.36;
58 
59 min_gap(2, 8, 10, 11, 15);
60 min_gap(1, 5, 6, 7, 14);
61 min_gap(8, 20, 25, 28);
62 
63 sub min_gap(@ints) {
64    say "Input: (" . join(", ", @ints) . ")";
65    my $min = undef;
66    my $elem = undef;
67    foreach my $i (1..$#ints) {
68       my $gap = $ints[$i] - $ints[$i-1];
69       if ( ! defined($min) or $gap < $min ) {
70          $min = $gap;
71          $elem = $ints[$i];
72       }
73    }
74    say "Output: $elem";
75 }