Peter’s blog ✴ Week 387 ✴ 17 August 2026
THE WEEKLY CHALLENGE
Ones and atoms
You are given a binary string. Write a script to re-arrange the given binary string so that all occurrences of “01” are simultaneously replaced with “10” and this is repeated until no occurrences of “01” exist.
Finally return the total steps needed.
Example 1 Input: $str = '111000' Output: 0 The string already has all 1s on the left and 0s on the right. There are no occurrences of '01', so zero step needed. Example 2 Input: $str = '00011' Output: 4 Step 1: '00101' Step 2: '01010' Step 3: '10100' Step 4: '11000' Example 3 Input: $str = '01011' Output: 3 Step 1: '10101' Step 2: '11010' Step 3: '11100' Example 4 Input: $str = '010101' Output: 3 Step 1: '101010' Step 2: '110100' Step 3: '111000' Example 5 Input: $str = '00001' Output: 4 Step 1: '00010' Step 2: '00100' Step 3: '01000' Step 4: '10000'
Once I got my head around this I found an easily understood one line solution:
$total ++ while $string =~ s|01|10|g;
The while with a g modifier copes with the requirement
for a 'step' to switch all the 01s to 10s in a single
step, and the $total ++ counts
those steps as required.
#!/usr/bin/perl
# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge/387/1
use v5.26; # The Weekly Challenge - 2026-08-17
use utf8; # Week 387 - task 1 - Rearrange binary string
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;
rearrange_binary_string('111000');
rearrange_binary_string('00011');
rearrange_binary_string('01011');
rearrange_binary_string('010101');
rearrange_binary_string('00001');
sub rearrange_binary_string {
my ($n, $string, $total, $c, $j);
# initialise
$n = $total = 0;
$string = $_[0];
$total ++ while $string =~ s|01|10|g;
say qq[\nInput: '$string' ];
say qq[Output: $total];
}
7 lines of code
Completed after the closing date and not submitted to GitHub
Input: '111000' Output: 0 Input: '11000' Output: 4 Input: '11100' Output: 3 Input: '111000' Output: 3 Input: '10000' Output: 4
Any content of this website which has been created by Peter Campbell Smith is in the public domain