Peter
Peter Campbell Smith

Middle aged and oldies

Weekly challenge 231 — 21 August 2023

Week 231 - 21 Aug 2023

Task 1

Task — Min max

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.

Examples


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.

Analysis

For this, I succumbed to the temptation to use a one-liner. What it does is:

  • If there are fewer than 3 elements in the array, return -1, else ...
  • Sort the array and the 2nd to 2nd-last elements are the answer.

Try it 

Try running the script with any input, for example:
5, 2, 3, 7, 9


Script


#!/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])) . ')';
}

Output


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)

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