Peter’s blog ✴ Week 398 ✴ 2 November 2026

THE WEEKLY CHALLENGE
Divisible and difference

The Perl Camel

Task 1

Divisible average

You are given an array of positive integers. Write a script to return the closest integer to the mean value of all even integers that are divisible by 3. If none is divisible, return 0.

Examples


Example 1
Input: @arr = (18, 5, 7, 11)
Output: 18
18 is the only even number and divisible by 3.
Average: 18 / 1 = 18.

Example 2
Input: @arr = (6, 12, 18, 24, 30, 40)
Output: 18
The qualifying numbers are 6, 12, 18, 24, and 30.
Average: (6 + 12 + 18 + 24 + 30) / 5 = 90 / 5 = 18

Example 3
Input: @arr = (3, 9, 15, 21, 27)
Output: 0
None of the elements are even.
Since no elements qualify, return 0.

Example 4
Input: @arr = (6, 12, 14, 20)
Output: 9
The qualifying numbers are 6 and 12.
Average: (6 + 12) / 2 = 9.

Example 5
Input: @arr = (6, 6, 6, 12, 12)
Output: 8
All five numbers are even and divisible by 3.
Average: (6 + 6 + 6 + 12 + 12) / 5 = 8.4 => 8

Analysis

An easy challenge with not much to do other than follow the instructions. The edge case where no integers are multiples of 6 is easily handled.

I completed this challenge on my Android phone on a moving train using AndFTP, QuickEdit and Termius. I was pleasantly surprised to find that QuickEdit can execute a Perl script, apparently on the phone.

Try it 

Your input:



eg: 5, 6, 11, 12, 13, 18

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge/398/1

use v5.26;    # The Weekly Challenge - 2026-11-02
use utf8;     # Week 398 - task 1 - Divisible average
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;

divisible_average(18, 5, 7, 11);
divisible_average(6, 12, 18, 24, 30, 40);
divisible_average(3, 9, 15, 21, 27);
divisible_average(6, 12, 14, 20);
divisible_average(6, 6, 6, 10, 12);

sub divisible_average {
    
    my (@array, @sixes, $sum, $result);
    
    # initialise    
    @array = @_;
    
    # extract multiples of 6
    @sixes = grep {$_ / 6 == int($_ / 6)} @array;

    # sum and rounded average
    if (@sixes) {
        $sum += $_ for @sixes;
        $result = int($sum / @sixes + 0.5);
    }
    
    # report
    say qq[\nInput:  (] . join(', ', @array) . ')';
    say qq[Output: ] . ($result or 0);
}

9 lines of code

Output from script


Input:  (18, 5, 7, 11)
Output: 18

Input:  (6, 12, 18, 24, 30, 40)
Output: 18

Input:  (3, 9, 15, 21, 27)
Output: 0

Input:  (6, 12, 14, 20)
Output: 9

Input:  (6, 6, 6, 10, 12)
Output: 8

 

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