Camel
Peter
Peter Campbell Smith

Deduplicate
and going up

Weekly challenge 340 — 22 September 2025

Week 340: 22 Sep 2025

Task 2

Task — Ascending numbers

You are given a string, $str, which is a list of tokens separated by a single space. Every token is either a positive number consisting of digits 0-9 with no leading zeros, or a word consisting of lowercase English letters. Write a script to check if all the numbers in the given string are strictly increasing from left to right.

Examples


Example 1
Input: $str = 'The cat has 3 kittens 7 toys 10 beds'
Output: true
Numbers 3, 7, 10 - strictly increasing.

Example 2
Input: $str = 'Alice bought 5 apples 2 oranges 9 bananas'
Output: false

Example 3
Input: $str = 'I ran 1 mile 2 days 3 weeks 4 months'
Output: true

Example 4
Input: $str = 'Bob has 10 cars 10 bikes'
Output: false

Example 5
Input: $str = 'Zero is 0 one is 1 two is 2'
Output: true

Analysis

There seems little alternative to inspecting all the tokens which are numbers, returning 'false' if any isn't greater than the preceding one and otherwise returning 'true'.

So that's what I did.

As always, in real life I would check the assertions made in the task statement, and ask the client a couple of pertinent questions such as:

  • What should I return if there are no numbers? (I've assumed 'true')
  • Are you regarding 0 as a positive number with no leading zeroes? (I've assumed yes)

Try it 

Try running the script with any input:



example: 3 times 5 makes 15

Script


#!/usr/bin/perl

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

use v5.26;    # The Weekly Challenge - 2025-09-22
use utf8;     # Week 340 - task 2 - Ascending numbers
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;

ascending_numbers('the 1 cat sat on the 2 mats');
ascending_numbers('the 2 cats sat on the 1 mat');
ascending_numbers('the 3 cats sat on the 3 mats');
ascending_numbers('one 1 two 2 three 3 four 4 five six 5 6 oops 5');
ascending_numbers('0');
ascending_numbers('cat');

sub ascending_numbers {
    
    my ($string, $last);
    
    # initialise
    $string = $_[0];
    say qq[\nInput:  '$string'];
    $last = -1;
    
    # loop over numbers
    while ($string =~ m|(\d+)|g) {
        
        # ok
        if ($1 > $last) {
            $last = $1;
            next;
        }
        
        # not ok
        say qq[Output: false ($1)];
        return;
    }
    say qq[Output: true];
}

Output


Input:  'the 1 cat sat on the 2 mats'
Output: true

Input:  'the 2 cats sat on the 1 mat'
Output: false (1)

Input:  'the 3 cats sat on the 3 mats'
Output: false (3)

Input:  'one 1 two 2 three 3 four 4 five six 5 6 oops 5'
Output: false (5)

Input:  '1'
Output: true

Input:  'cat'
Output: true

 

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