Camel
Peter
Peter Campbell Smith

Fun with arrays

Weekly challenge 351 — 8 December 2025

Week 351: 8 Dec 2025

Task 1

Task — Special average

You are given an array of integers. Write a script to return the average excluding the minimum and maximum of the given array.

Examples


Example 1
Input: @ints = (8000, 5000, 6000, 2000, 3000, 7000)
Output: 5250
Min: 2000
Max: 8000
Avg: (3000+5000+6000+7000)/4 = 21000/4 = 5250

Example 2
Input: @ints = (100_000, 80_000, 110_000, 90_000)
Output: 95_000
Min: 80_000
Max: 110_000
Avg: (100_000 + 90_000)/2 = 190_000/2 = 95_000

Example 3
Input: @ints = (2500, 2500, 2500, 2500)
Output: 0
Min: 2500
Max: 2500
Avg: 0

Example 4
Input: @ints = (2000)
Output: 0
Min: 2000
Max: 2000
Avg: 0

Example 5
Input: @ints = (1000, 2000, 3000, 4000, 5000, 6000)
Output: 3500
Min: 1000
Max: 6000
Avg: (2000 + 3000 + 4000 + 5000)/4 = 14000/4 = 3500

Analysis

On the KISS principle (Keep It Simple, Stupid) I sorted the array, summed from the 2nd to the 2nd last elements and divided by the length of the array minus 2.

That's nice readable code, but is it efficient? I tried it with a million random integers in the range 0 - 999,999 and it came up with 499595.1 in under 2 seconds - and about half of that was used to generate the random numbers. So I think that's fast enough.

I take slight issue with example 4 which regards the average of an empty set of numbers as being 0; for the task as stated I treat the input as invalid unless there are at least 3 elements in the array. In real life one would ask the client what they want to happen if there were fewer than 3.

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 - 2025-12-08
use utf8;     # Week 351 - task 1 - Special average
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;

special_average(8000, 5000, 6000, 2000, 3000, 7000);
special_average(100_000, 80_000, 110_000, 90_000);
special_average(2500, 2500, 2500, 2500);
special_average(1, 3);

sub special_average {
    
    my (@sorted, $sum);
    
    # initialise
    say qq[\nInput:  (] . join(', ', @_) . ')';
    
    # need at lleast 3 elements
    if (@_ > 2) {
        
        # calculate average
        @sorted = sort {$a <=> $b} @_;
        $sum += $sorted[$_] for 1 .. @sorted - 2;
        say qq[Output: ] . ($sum / (@sorted - 2));
    
    # error
    } else {
        say qq[Output: need at least 3 elements];
    }
}


Output


Input:  (8000, 5000, 6000, 2000, 3000, 7000)
Output: 5250

Input:  (100000, 80000, 110000, 90000)
Output: 95000

Input:  (2500, 2500, 2500, 2500)
Output: 2500

Input:  (1, 3)
Output: need at least 3 elements

 

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