Middle aged and oldies
Weekly challenge 231 — 21 August 2023
Week 231: 21 Aug 2023
You are given an array of distinct integers. Write a script to find all elements that are neither the minimum nor maximum. Return -1 if you can’t.
Example 1 Input: @ints = (3, 2, 1, 4) Output: (3, 2) The minimum is 1 and maximum is 4 in the given array. So (3, 2) is neither min nor max. Example 2 Input: @ints = (3, 1) Output: -1 Example 3 Input: @ints = (2, 1, 3) Output: (2) The minimum is 1 and maximum is 3 in the given array. So 2 is neither min nor max.
For this, I succumbed to the temptation to use a one-liner. What it does is:
#!/usr/bin/perl use v5.16; # The Weekly Challenge - 2023-08-21 use utf8; # Week 231 task 1 - Min max use strict; # Peter Campbell Smith use warnings; # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge min_max(3, 2, 1, 4); min_max(7, 2, 8, 4, 5, 1, 6, 0, 11, 34, 23, 76, 99, 24); min_max(5, 6); min_max(7, 6, 5); sub min_max { say qq[\nInput: (] . join(', ', @_) . ')'; say qq[Output: (] . (scalar @_ < 3 ? -1 : join(', ', (sort {$a <=> $b} @_)[1 .. scalar @_ - 2])) . ')'; }
Input: (3, 2, 1, 4) Output: (2, 3) Input: (7, 2, 8, 4, 5, 1, 6, 0, 11, 34, 23, 76, 99, 24) Output: (1, 2, 4, 5, 6, 7, 8, 11, 23, 24, 34, 76) Input: (5, 6) Output: (-1) Input: (7, 6, 5) Output: (6)
Any content of this website which has been created by Peter Campbell Smith is in the public domain