Peter
Peter Campbell Smith

Three in the middle
and stock answer

Weekly challenge 135 — 18 October 2021

Week 135: 18 Oct 2021

Task 1

Task — Middle 3-digits

You are given an integer. Write a script find out the middle 3 digits of the given integer, if possible, otherwise throw sensible error.

Examples


Example 1
Input: $n = 1234567
Output: 345

Example 2
Input: $n = -123
Output: 123

Example 3
Input: $n = 1
Output: too short

Example 4
Input: $n = 10
Output: even number of digits

Analysis

A combination of length() and substr() will give us the desired result very simply, but first we have to strip any leading minus sign, eliminate 'even number of digits' and 'too short' - in that order to match the examples - and I added 'not an integer'.

Then it's just substr($n, (length($n) - 3) / 2, 3).

Try it 

Try running the script with any input:



example: 1122211

Script


#!/usr/bin/perl

# Peter Campbell Smith - 2021-10-18
# PWC 135 task 1

use v5.20;
use warnings;
use strict;

middle_3_digits($_) for (1234567, -123, 1, 10, 98765432123456789);

sub middle_3_digits {

    my ($n, $length);
    
    $n = shift;
    print qq[\nInput:  $n\nOutput: ];

    # output
    $n =~ s|^-||;
    $length = length($n);

    if ($n !~ m|^\d+$|) {
        say 'not an integer';
        
    } elsif (($length & 1) == 0) {
        say 'even number of digits';

    } elsif ($length < 3) {
        say 'too short';
        
    } else {   # valid number
        say substr($n, ($length - 3) / 2, 3);
    }
}

Output


Input:  1234567
Output: 345

Input:  -123
Output: 123

Input:  1
Output: too short

Input:  10
Output: even number of digits

Input:  98765432123456789
Output: 212

 

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