Peter’s blog ✴ Week 309 ✴ 17 February 2025

THE WEEKLY CHALLENGE
Mind the gap

The Perl Camel

Task 2

Min diff

You are given an array of integers, @ints. Write a script to find the minimum difference between any two elements.

Examples


Example 1
Input: @ints = (1, 5, 8, 9)
Output: 1
1, 5 => 5 - 1 => 4
1, 8 => 8 - 1 => 7
1, 9 => 9 - 1 => 8
5, 8 => 8 - 5 => 3
5, 9 => 9 - 5 => 4
8, 9 => 9 - 8 => 1

Example 2
Input: @ints = (9, 4, 1, 7)
Output: 2
9, 4 => 9 - 4 => 5
9, 1 => 9 - 1 => 8
9, 7 => 9 - 7 => 2
4, 1 => 4 - 1 => 3
4, 7 => 7 - 4 => 3
1, 7 => 7 - 1 => 6

Analysis

I don't have much to say about this one as the code is almost the same as for task 1. Clearly, if we sort @ints the smallest gap will be between 2 consecutive elements, and the rest is just slightly different output.

And in case you wondered, see also Mind the gap.

Perl Weekly’s review

from PW issue 709

A complete solution that anyone can understand and follow. Bonus, you get DIY tool to try as well.

This review may cover either or both challenges for this week.

Try it 

Try running the script with any input:



example: -14, 23, -26, 14, -31

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2025-02-17
use utf8;     # Week 309 - task 2 - Min diff
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';

min_diff(1, 5, 8, 9);
min_diff(9, 4, 1, 7);

my @ints;
push @ints, int(rand(1000)) for 0 .. 11;
min_diff(@ints);

sub min_diff {
    
    my (@ints, $min_gap, $gap, $j, $where);
    
    # initialise
    @ints = sort {$a <=> $b} @_;    
    $min_gap = 1e9;
    
    # loop over @ints starting at the second element
    for $j (1 .. $#ints) {
        $gap = $ints[$j] - $ints[$j - 1];
        next if $gap >= $min_gap;
        
        # found the smallest so far
        $min_gap = $gap;
        $where = qq[$ints[$j - 1] and $ints[$j]];
    }
    
    say qq[\nInput:  \@ints = (] . join(', ', @_) . ')';
    say qq[Output: minimum difference is $min_gap between $where];
}

11 lines of code

Output from script


Input:  @ints = (1, 5, 8, 9)
Output: minimum difference is 1 between 8 and 9

Input:  @ints = (9, 4, 1, 7)
Output: minimum difference is 2 between 7 and 9

Input:  @ints = (419, 772, 368, 569, 478, 471, 282, 858, 
   420, 910, 586, 746)
Output: minimum difference is 1 between 419 and 420

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain