Peter’s blog ✴ Week 106 ✴ 29 March 2021

THE WEEKLY CHALLENGE
Mind the gap, and repeat

The Perl Camel

Task 1

Maximum gap

You are given an array of integers @N.

Write a script to display the maximum difference between two successive elements once the array is sorted.

If the array contains only 1 element then display 0.

Examples


Example 1
Input: @N = (2, 9, 3, 5)
Output: 4

Example 2
Input: @N = (1, 3, 8, 2, 0)
Output: 5

Example 3
Input: @N = (5)
Output: 0

Analysis

There may be a more elegant or concise solution, but nothing beats:

  • Sort @N
  • Loop over @N to find the smallest gap

for comprehensibility, not with the edge case of a single-member array also handled.

I am sorry that the 'Try it' feature is currently working very slowly or not at all owing to some issue with my web hosting provider.

Try it 

Try running the script with any input:



example: 3, 1, 4, 1, 5, 9

Script


#!/usr/bin/perl

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

use v5.26;    # The Weekly Challenge - 2021-03-29
use utf8;     # Week 106 - task 1 - Maximum gap
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;

maximum_gap(3);
maximum_gap(1, 2, 3, 4, 5);
maximum_gap(1, 16, 3, 15, 6, 10, 15);
maximum_gap(-7, -3, 1, 2, 3, 4);

sub maximum_gap {
    
    my (@n, $result, $gap, $j);
    
    # initialise
    @n = @_;
    say qq[\nInput:  (] . join(', ', @n) . ')';
    
    # find biggest gap
    $result = 0;
    if (@n > 1) {
        @n = sort {$a <=> $b} @n;
        for $j (1 .. $#n) {
            $gap = $n[$j] - $n[$j - 1];
            $result = $gap if $gap > $result;
        }
    }
    
    # report
    say qq[Output: $result];
}

11 lines of code
Completed after the closing date and not submitted to GitHub

Output from script


Input:  (3)
Output: 0

Input:  (1, 2, 3, 4, 5)
Output: 1

Input:  (1, 16, 3, 15, 6, 10, 15)
Output: 5

Input:  (-7, -3, 1, 2, 3, 4)
Output: 4

 

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