Task 1: Rearrange Spaces
"Text Tuning: Harmonizing White Space Between Words!"
Rearrange spaces in a string to distribute them equally between words, with any remainder placed at the end.
The Strategy: First, count the total number of spaces and extract all non-empty words. If there's only one word, all spaces go after it. Otherwise, calculate the number of gaps (word count - 1). Divide total spaces by gaps to get spaces per gap, and use the modulo operator for the remainder. Join the words using the calculated gap size and append the remainder.
Perl Implementation
sub rearrange_spaces ($str) {
my $num_spaces = ( $str =~ tr/ // );
my @words = grep { length($_) } split /\s+/, $str;
my $num_words = scalar @words;
if ( $num_words == 1 ) {
return $words[0] . ( ' ' x $num_spaces );
}
my $num_gaps = $num_words - 1;
my $spaces_per_gap = int( $num_spaces / $num_gaps );
my $remainder = $num_spaces % $num_gaps;
return join( ( ' ' x $spaces_per_gap ), @words ) . ( ' ' x $remainder );
}
Python Implementation
def rearrange_spaces(text: str) -> str:
num_spaces = text.count(" ")
words = text.split()
num_words = len(words)
if num_words == 1:
return words[0] + (" " * num_spaces)
num_gaps = num_words - 1
spaces_per_gap = num_spaces // num_gaps
remainder = num_spaces % num_gaps
return (" " * spaces_per_gap).join(words) + (" " * remainder)