Peter’s blog ✴ Week 390 ✴ 7 September 2026

THE WEEKLY CHALLENGE
Multiply and order

The Perl Camel

Task 1

Decode string

You are given an encoded string. Write a script to return the decoded string of the given encoded string.

The encoding rule is: K[encoded_string], where the encoded_string inside the square brackets is repeated exactly K > 0 times.

Examples


Example 1
Input: $str = '2[3[a]]'
Output: 'aaaaaa'
3[a]    => aaa
2[3[a]] => aaa aaa

Example 2
Input: $str = '10[a]'
Output: 'aaaaaaaaaa'

Example 3
Input: $str = 'a2[b]c3[d]e'
Output: 'abbcddde'

Example 4
Input: $str = '2[a2[b]c]'
Output: 'abbcabbc'

Example 5
Input: $str = '1[a]2[b3[c]]'
Output: 'abcccbccc'

Analysis

This is similar - though simpler - than week 387’s task 2.

I parse the input string left to right, keeping track of the current multiplier (initialised to 1) on a stack.

When I encounter a number followed by a '[' I push the old multiplier onto the stack and multiply the current multiplier by the number.

When I encounter one or more letters I output them for the current multiplier times.

When I find a ']' I pop the multiplier off the stack.

And that does it.

Try it 

Your input:



eg: co2[m]i2[te]

Script


#!/usr/bin/perl

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

use v5.26;    # The Weekly Challenge - 2026-09-07
use utf8;     # Week 390 - task 1 - Decode string
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;

decode_string('2[3[a]]');
decode_string('10[a]');
decode_string('a2[b]c3[d]e');
decode_string('2[a2[b]c]');
decode_string('1[a]2[b3[c]]');
decode_string('4[x3[y2[f]]]');
decode_string('co2[m]i2[t]2[e]');
decode_string('3[bang]');

sub decode_string {
    
    my ($f, $m, %c, @s, $o);
            
    # initialise
    $f = shift;
    say qq[\nInput:  '$f'];
    $m = 1;
    %c = ();

    # scan input
    while ($f) {
        
        # [ = increase multiplier
        if ($f =~ m|^(\d+)\[(.*)|) {
            push @s, $1;
            $m *= $1;
        
        # repeat letter $m times
        } elsif ($f =~ m|^([a-z]+)(.*)|) {
            $o .= $1 x $m;
        
        # ] = decrease multiplier
        } elsif ($f =~ m|^(\])(.*)|) {
            $m /= pop @s;
        
        } else {
            last;
        }
        $f = $2;
    }
    
    # report
    say qq[Output: '$o'];
}

18 lines of code

Output from script


Input:  '2[3[a]]'
Output: 'aaaaaa'

Input:  '10[a]'
Output: 'aaaaaaaaaa'

Input:  'a2[b]c3[d]e'
Output: 'abbcddde'

Input:  '2[a2[b]c]'
Output: 'aabbbbcc'

Input:  '1[a]2[b3[c]]'
Output: 'abbcccccc'

Input:  '4[x3[y2[f]]]'
Output: 'xxxxyyyyyyyyyyyyffffffffffffffffffffffff'

Input:  'co2[m]i2[te]'
Output: 'committee'

 

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