Echo and wordy numbers
Weekly challenge 362 — 23 February 2026
Week 362: 23 Feb 2026
You are given a string containing lowercase letters. Write a script to transform the string based on the index position of each character (starting from 0). For each character at position i, repeat it i + 1 times.
Example 1 Input: 'abca' Output: 'abbcccaaaa' Index 0: 'a' -> repeated 1 time -> 'a' Index 1: 'b' -> repeated 2 times -> 'bb' Index 2: 'c' -> repeated 3 times -> 'ccc' Index 3: 'a' -> repeated 4 times -> 'aaaa' Example 2 Input: 'xyz' Output: 'xyyzzz' Index 0: 'x' -> 'x' Index 1: 'y' -> 'yy' Index 2: 'z' -> 'zzz' Example 3 Input: 'code' Output: 'coodddeeee' Index 0: 'c' -> 'c' Index 1: 'o' -> 'oo' Index 2: 'd' -> 'ddd' Index 3: 'e' -> 'eeee' Example 4 Input: 'hello' Output: 'heelllllllooooo' Index 0: 'h' -> 'h' Index 1: 'e' -> 'ee' Index 2: 'l' -> 'lll' Index 3: 'l' -> 'llll' Index 4: 'o' -> 'ooooo' Example 5 Input: 'a' Output: 'a' Index 0: 'a' -> 'a'
You can do this in a one-liner:
$output .= substr($input, $_, 1) x ($_ + 1) for 0 .. length($input) - 1;
but I felt it was clearer to split the input
into @chars, and then the line that does the work
is easier to understand.
I might be forgiven for thinking 'Why would you ever need to do that?'
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2026-02-23 use utf8; # Week 362 - task 1 - Echo chamber use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; echo_chamber('xyz'); echo_chamber('hello'); echo_chamber('challenge'); echo_chamber(''); echo_chamber('pi=3.14159'); sub echo_chamber { my ($input, @chars, $output); # just do it @chars = split('', $_[0]); $output .= $chars[$_] x ($_ + 1) for 0 .. $#chars; say qq[\nInput: '$_[0]']; say qq[Output: '] . (defined $output ? $output : '') . "'"; }
Input: 'xyz' Output: 'xyyzzz' Input: 'hello' Output: 'heelllllllooooo' Input: 'challenge' Output: 'chhaaallllllllleeeeeennnnnnnggggggggeeeeeeeee' Input: '' Output: '' Input: 'pi=3.14159' Output: 'pii===3333.....111111444444411111111555555555999 9999999'
Any content of this website which has been created by Peter Campbell Smith is in the public domain