Course of Raku / Addendum 🆕 / Working with data / Text and strings / Exercises / Run-length encoding
Solution: Run-length encoding
Here is a possible solution to the task.
Code
my $text = 'aaabbbbcc';
my $encoded = '';
for $text ~~ m:g/ (.) $0* / -> $match {
$encoded ~= $match[0] ~ $match.chars;
}
say $encoded;🦋 You can find the source code in the file run-length.raku.
Output
a3b4c2Comments
The pattern
(.) $0*captures one character and then matches as many further copies of it as follow — one whole run per match.m:gcollects every run.For each run,
$match[0]is the repeated letter and$match.charsis how long the run is, so the two together give entries likea3.