The Weekly Challenge 322

String Formatting & Ranking Arrays!

Original Challenge Link

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))

Task 2: Rank Array

"Sorting Status: Assigning Ranks with Ties!"

Replace each element in an array with its rank, where the lowest value is rank 1 and identical values share a rank.

The Strategy: To assign ranks, we first find the unique values in the array and sort them in ascending order. We then create a mapping (hash or dictionary) where each value is associated with its position in the sorted unique list (starting from 1). Finally, we iterate through the original array and replace each element with its mapped rank.
Perl Implementation
sub rank_array ($ints) {
    return [] if !@$ints;

    my @sorted_unique = sort { $a <=> $b } uniq(@$ints);
    my %rank_of;
    for my $idx ( 0 .. $#sorted_unique ) {
        $rank_of{ $sorted_unique[$idx] } = $idx + 1;
    }

    return [ map { $rank_of{$_} } @$ints ];
}
Python Implementation
def rank_array(values: Sequence[int]) -> list[int]:
    unique_sorted = sorted(set(values))
    rank_of = {value: idx + 1 for idx, value in enumerate(unique_sorted)}
    return [rank_of[value] for value in values]