The Weekly Challenge 362

Letter Multiplication & Number Spelling Magic!

Original Challenge Link | My Solutions

Task 1: Echo Chamber

"Letter Amplification: When Each Letter Gets Its Moment to Shine!"

This week's first task involves transforming a string where each character is repeated based on its position (starting from 0). The character at index i is repeated i+1 times.

The Strategy: Iterate through each character with its index. For each character, repeat it (index + 1) times and append to the result.
Perl Implementation
sub echo_chamber {
    my ($str) = @_;
    $str =~ s/(.)/ $1 x (pos($str) + 1) /ge;
    return $str;
}
Python Implementation
def echo_chamber(s: str) -> str:
    result = ""
    for i, char in enumerate(s):
        result += char * (i + 1)
    return result

Task 2: Spellbound Sorting

"Word ABCs: When Numbers Put on Their Spelling Hats!"

The second task involves sorting an array of integers alphabetically by their English word representation.

The Strategy: Convert each number to its English word representation, sort by those words, then return the original numbers in the new order.
Perl Implementation
sub spellbound_sort {
    my (@nums) = @_;
    my @words = map { number_to_words($_) } @nums;
    my @sorted_idx = sort { $words[$a] cmp $words[$b] } 0..$#nums;
    return @nums[@sorted_idx];
}
Python Implementation
def spellbound_sort(nums):
    words = [number_to_words(n) for n in nums]
    sorted_indices = sorted(range(len(words)), key=lambda i: words[i])
    return [nums[i] for i in sorted_indices]