perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 309 - Task 2: Min Diff

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-309/#TASK2
 3 #
 4 # Task 2: Min Diff
 5 # ================
 6 #
 7 # You are given an array of integers, @ints.
 8 #
 9 # Write a script to find the minimum difference between any two elements.
10 #
11 ## Example 1
12 ##
13 ## Input: @ints = (1, 5, 8, 9)
14 ## Output: 1
15 ##
16 ## 1, 5 => 5 - 1 => 4
17 ## 1, 8 => 8 - 1 => 7
18 ## 1, 9 => 9 - 1 => 8
19 ## 5, 8 => 8 - 5 => 3
20 ## 5, 9 => 9 - 5 => 4
21 ## 8, 9 => 9 - 8 => 1
22 #
23 ## Example 2
24 ##
25 ## Input: @ints = (9, 4, 1, 7)
26 ## Output: 2
27 ##
28 ## 9, 4 => 9 - 4 => 5
29 ## 9, 1 => 9 - 1 => 8
30 ## 9, 7 => 9 - 7 => 2
31 ## 4, 1 => 4 - 1 => 3
32 ## 4, 7 => 7 - 4 => 3
33 ## 1, 7 => 7 - 1 => 6
34 #
35 ############################################################
36 ##
37 ## discussion
38 ##
39 ############################################################
40 #
41 # We just calculate all possible differences, keeping track
42 # of the minimum.
43 
44 use v5.36;
45 
46 min_diff(1, 5, 8, 9);
47 min_diff(9, 4, 1, 7);
48 
49 sub min_diff(@ints) {
50    say "Input: (" . join(", ", @ints) . ")";
51    return say "Output: undef" unless $#ints > 0;
52    my $min = abs($ints[0] - $ints[1]);
53    foreach my $i (0..$#ints) {
54       foreach my $j ($i+1..$#ints) {
55          my $diff = abs($ints[$i] - $ints[$j]);
56          $min = $diff if $diff < $min;
57       }
58    }
59    say "Output: $min";
60 }