Peter’s blog ✴ Week 374 ✴ 18 May 2026
THE WEEKLY CHALLENGE
Lots of repetition
You are given a string containing 0-9 digits only. Write a script to return the largest number with all digits the same in the given string.
Example 1 Input: $str = '6777133339' Output: 3333 Example 2 Input: $str = '1200034' Output: 4 Example 3 Input: $str = '44221155' Output: 55 None found. Example 4 Input: $str = '88888' Output: 88888 Example 5 Input: $str = '11122233' Output: 222
This can be solved simply with a slightly unusual regex:
$string =~ m|((\d)\2*)|g
This shows that captured substrings such as $1 or $2 can be nested.
The numbering depends on the relative position of the opening bracket. So in
the above:
\d captures (say) '3'.
(\d),
and its '(' is the second to appear, so '3' is assigned to $2.
m||| is equivalent to
'$2' outside the regex, so
the outer brackets capture a digit - \d - followed by 0 or more
further identical digits, eg 333.
while captures
successive groups of 1 or more identical digits.#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2026-05-18 use utf8; # Week 374 - task 2 - Largest same-digits number use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; largest_samedigits_number('6777133339'); largest_samedigits_number('1200034'); largest_samedigits_number('44221155'); largest_samedigits_number('88888'); largest_samedigits_number('0'); largest_samedigits_number('1'); my $s; # 500 random digits $s .= int(rand(10)) for 1 .. 500; largest_samedigits_number($s); sub largest_samedigits_number { my ($string, $largest); # initialise $string = $_[0]; $largest = 0; while ($string =~ m|((\d)\2*)|g) { $largest = $1 if $1 > $largest; } say qq[\nInput: '$string']; say qq[Output: '$largest']; }
8 lines of code
Input: '6777133339' Output: '3333' Input: '1200034' Output: '4' Input: '44221155' Output: '55' Input: '88888' Output: '88888' Input: '0' Output: '0' Input: '1' Output: '1' Input: '170239718067938306589606930797595541097991967776679705470418523648 2936333697117800410263143292185155478557979524464053132399177948337 8686862440502973678330755001118122295581856188880694766700574607193 9958689162716249159220879265885211739475251104420375943629595281763 0115031800662306828419319421741686830717669481677313927000921767474 5226933753604138913581734273543166788437204759920078481419885859401 8114563488450028350048871826334643332779638874345616232692503727570 54011460025532297513456973576880' Output: '8888'
Any content of this website which has been created by Peter Campbell Smith is in the public domain