Camel
Peter
Peter Campbell Smith

Sequence and squares

Weekly challenge 116 — 7 June 2021

Week 116: 7 Jun 2021

Task 1

Task — Number sequence

You are given a number $N >= 10. Write a script to split the given number such that the difference between two consecutive numbers is always 1 without any having a leading 0.

Print the given number if it impossible to split the number.

Examples


Input: $N = 1234
Output: 1,2,3,4

Input: $N = 91011
Output: 9,10,11

Input: $N = 10203
Output: 10203 as it is impossible to split satisfying 
the conditions.

Analysis

I solved this by taking the first $digits digits of the number and checking if that $value was followed by $value + 1 and so on to the end of the string.

Clearly the maximum value of $digits has to be less than half the length of the initial number as we need at least two numbers to form a sequence.

Try it 

Try running the script with any input:



example: 9899100101

Script


#!/usr/bin/perl

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

use v5.26;    # The Weekly Challenge - 2021-06-07
use utf8;     # Week 116 - task 1 - Number sequence
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;

number_sequence(12345);
number_sequence(9101011);
number_sequence(9991000100110021003);
number_sequence(99100101);
number_sequence(55555);
number_sequence(12346);

sub number_sequence {
    
    my ($input, $digits, $start, $rest, $output);
    
    # initialise
    $input = $_[0];
    say qq[\nInput:  $input];
    
    # loop over possible lengths of starting number
    for $digits (1 .. int(length($input) / 2)) {
        $start = substr($input, 0, $digits);
        $output = qq[$start, ];
        $rest = substr($input, $digits);
        
        # check the following numbers
        while ($rest) {
            $start ++;
            last unless $rest =~ m|^$start(.*)|;
            $output .= qq[$start, ];
            $rest = $1;
        }
        
        # used the whole input number, so success!
        unless ($rest) {
            say qq[Output: ] . substr($output, 0, -2);
            return;
        }
    }
    
    # failed
    say qq[Output: $input cannot be split];
}

last updated 2026-03-24 — 17 lines of code

Output


Input:  91011
Output: 9, 10, 11

Input:  9991000100110021003
Output: 999, 1000, 1001, 1002, 1003

Input:  99100101
Output: 99, 100, 101

Input:  55555
Output: 55555 cannot be split

Input:  12346
Output: 12346 cannot be split

 

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