The Weekly Challenge 355

Number Formatting & Mountain Validation!

Original Challenge Link

Task 1: Thousand Separator

"Comma Chameleon: Making Numbers Readable!"

This week's first task involves formatting numbers with thousand separators. Given a positive integer, we need to add commas as thousand separators and return the result as a string. This is a common formatting requirement for displaying large numbers in a human-readable format.

The Strategy: We reverse the string representation of the number, then use regex to insert commas every three digits from the right. Finally, we reverse the string back to get the properly formatted number. This approach handles numbers of any length efficiently.
Perl Implementation
sub thousand_separator ($int) {
    ($int) = $INT_CHECK->($int);
    die 'Expected a positive integer' if $int <= 0;

    my $s = reverse "$int";
    $s =~ s/(\d{3})(?=\d)/$1,/g;
    return scalar reverse $s;
}
Python Implementation
def thousand_separator(value: int) -> str:
    """Format positive integer with commas as thousands separators."""
    if value <= 0:
        raise ValueError("Expected a positive integer")
    s = str(value)[::-1]
    parts = [s[i : i + 3] for i in range(0, len(s), 3)]
    return ",".join(part[::-1] for part in parts[::-1])

Task 2: Mountain Array

"Climbing the Peak: Array Validation Summit!"

The second task involves validating mountain arrays. An array is considered a mountain if it has at least 3 elements, strictly increases to a peak (not at the start or end), then strictly decreases to the end. We need to determine if a given array meets these criteria.

The Strategy: We first check if the array has at least 3 elements. Then we find the peak by moving forward while elements increase. We ensure the peak isn't at the start or end. Finally, we continue moving forward while elements decrease. If we reach the end, it's a valid mountain array.
Perl Implementation
sub is_mountain_array ($ints) {
    ($ints) = $ARR_CHECK->($ints);
    my $n = scalar @$ints;
    return 0 if $n < 3;

    my $i = 1;
    $i++ while $i < $n && $ints->[ $i - 1 ] < $ints->[$i];
    return 0 if $i == 1 || $i == $n;

    $i++ while $i < $n && $ints->[ $i - 1 ] > $ints->[$i];
    return $i == $n ? 1 : 0;
}
Python Implementation
def is_mountain_array(ints: Sequence[int]) -> bool:
    """Return True if ints forms a valid mountain array."""
    n = len(ints)
    if n < 3:
        return False

    i = 1
    while i < n and ints[i - 1] < ints[i]:
        i += 1
    if i == 1 or i == n:
        return False

    while i < n and ints[i - 1] > ints[i]:
        i += 1
    return i == n