The Weekly Challenge 360

Star-Padding & Word Rainbow Sort: Text Gets Weird!

Original Challenge Link | My Solutions

Task 1: Text Justifier

"Star-Padding: Making Text Look Good in the Center!"

This week's first task involves centering text within a specified width using asterisks as padding characters. Given a string and a width, we need to add asterisks on both sides to center the text.

The Strategy: Calculate the required padding (width - text length), then distribute it evenly on both sides. Use integer division for left padding and the remainder for right padding.
Perl Implementation
sub justify_text {
    my ($str, $width) = @_;
    my $pad = $width - length $str;
    return "*" x int($pad / 2) . $str . "*" x ($pad - int($pad / 2));
}
Python Implementation
def justify_text(s: str, width: int) -> str:
    pad = width - len(s)
    left = pad // 2
    right = pad - left
    return "*" * left + s + "*" * right

Task 2: Word Sorter

"Alphabetical Word Party: Everyone in the Right Order!"

The second task requires sorting words in a sentence alphabetically while preserving the original word case and punctuation.

The Strategy: Split the sentence into words, sort them alphabetically, then rejoin. The key is to handle multiple spaces correctly by using a more sophisticated split.
Perl Implementation
sub word_sorter {
    my ($sentence) = @_;
    my @words = grep { /\S/ } split /\s+/, $sentence;
    my @sorted = sort { lc($a) cmp lc($b) } @words;
    return join " ", @sorted;
}
Python Implementation
def word_sorter(sentence: str) -> str:
    words = [w for w in sentence.split() if w]
    sorted_words = sorted(words, key=lambda w: w.lower())
    return " ".join(sorted_words)