Peter’s blog ✴ Week 381 ✴ 6 July 2026
THE WEEKLY CHALLENGE
Same, smaller, greater
You are given an array of integers. Write a script to find the number of elements that have both a strictly smaller and greater element in the given array.
Example 1 Input: @int = (2,4) Output: 0 Not enough elements in the array. Example 2 Input: @int = (1, 1, 1, 1) Output: 0 Example 3 Input: @int = (1, 1, 4, 8, 12, 12) Output: 2 The elements are 4 and 8. Example 4 Input: @int = (3, 6, 6, 9) Output: 2 Both instances of 6. Example 5 Input: @int = (0, -5, 10, -2, 4) Output: 3 The elements are 0, -2, and 4.
To sort or not to sort, as Hamlet didn't say.
Sorting is overkill, but it's 33C here and I'm looking for the easy answer, which is:
$array[0] and less than $array[-1].
On a cooler day I might do a first pass through to find the largest and smallest, and a second pass to count the elements as above, but it would need to be a huge array to make an appreciable difference.
Peter maintains his well-established tradition of rendering intelligent explanations of the problems of the week tasks, 'Same Row Column' and 'Smaller Greater Element'. His take on these tasks is characterised by the ease of reading and clarity of the presented equations.
This review may cover either or both challenges for this week.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge/381/2 use v5.26; # The Weekly Challenge - 2026-07-06 use utf8; # Week 381 - task 2 - Smaller greater element use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; smaller_greater_element(1, 1, 1, 1); smaller_greater_element(4, 8, 12, 12, 1, 1); smaller_greater_element(9, 6, 6, 3); smaller_greater_element(0, -5, 10, -2, 4); my @x; push @x, int(rand(10)) + 1 for 1 .. 50; smaller_greater_element(@x); sub smaller_greater_element { my (@array, @explain, $n); # initialise say qq[\nInput: ] . join(', ', @_); @array = sort {$a <=> $b} @_; # look for candidates for $n (0 .. $#array) { push @explain, $array[$n] if ($array[$n] > $array[0] and $array[$n] < $array[-1]); } # report say qq[Output: ] . (@explain ? (scalar @explain . qq[ (] . join(', ', @explain) . ')') : 'none'); }
9 lines of code
Input: 1, 1, 1, 1 Output: none Input: 4, 8, 12, 12, 1, 1 Output: 2 (4, 8) Input: 9, 6, 6, 3 Output: 2 (6, 6) Input: 0, -5, 10, -2, 4 Output: 3 (-2, 0, 4) Input: 5, 9, 5, 8, 4, 7, 6, 5, 5, 1, 5, 6, 3, 5, 10, 3, 3, 5, 3, 8, 8, 3, 4, 7, 1, 10, 9, 2, 6, 5, 9, 4, 8, 3, 7, 9, 3, 5, 1, 8, 3, 5, 8, 7, 8, 3, 3, 3, 4, 3 Output: 45 (2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9)
Any content of this website which has been created by Peter Campbell Smith is in the public domain