Mind the gap, and repeat
Weekly challenge 106 — 29 March 2021
Week 106: 29 Mar 2021
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.
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
There may be a more elegant or concise solution, but nothing beats:
@N
@N to find the smallest gap
for comprehensibility, not with the edge case of a single-member array also handled.
#!/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
I completed this challenge after the closing date
and it has not
been submitted to GitHub
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