Task 1: String Format
"Dashing Data: Regrouping Characters from the End!"
Reformat a string by removing all dashes and grouping characters into chunks of size $ from right to left.
The Strategy: First, remove all existing dashes from the input string. If the resulting string is empty, return it. Otherwise, process the string from the end: repeatedly extract chunks of the specified size until the remaining string is shorter than or equal to that size. Collect these chunks and the remaining part, reverse the collection, and join them with dashes.
Perl Implementation
sub string_format ($str, $i) {
$str =~ s/-//g;
return '' if $str eq '';
my @groups;
while ( length($str) > $i ) {
my $chunk = substr( $str, -$i, $i, '' );
push @groups, $chunk;
}
push @groups, $str if $str ne '';
return join '-', reverse @groups;
}
Python Implementation
def string_format(text: str, size: int) -> str:
cleaned = text.replace("-", "")
if not cleaned:
return ""
groups: list[str] = []
while len(cleaned) > size:
groups.append(cleaned[-size:])
cleaned = cleaned[:-size]
groups.append(cleaned)
return "-".join(reversed(groups))