The Weekly Challenge 358

String Kung Fu: Max Values & Alphabet Shifts!

Original Challenge Link | My Solutions

Task 1: Max Str Value

"String Showdown: Who Wins the Value Battle?"

Find the max value of an alphanumeric string array - use numeric value if digits only, otherwise use string length.

The Strategy: For each string, check if it contains only digits. If so, convert to integer; otherwise use length. Track the maximum.
Perl Implementation
sub max_str_val {
    my @str = @_;
    my $max = 0;
    for (@str) {
        my $val = /^\d+$/ ? $_ : length $_;
        $max = $val if $val > $max;
    }
    return $max;
}
Python Implementation
def max_str_val(strings: list[str]) -> int:
    """Find max value: numeric if all digits, else length."""
    max_val = 0
    for s in strings:
        if s.isdigit():
            val = int(s)
        else:
            val = len(s)
        max_val = max(max_val, val)
    return max_val

Task 2: Encrypted String

"Alphabet Yoga: When Letters Do the Shuffle!"

Encrypt a string by shifting each character by N positions in the alphabet, wrapping around if needed.

The Strategy: For each character, calculate new position with modulo 26 arithmetic to handle wrapping.
Perl Implementation
sub encrypt_string {
    my ($str, $shift) = @_;
    $shift %= 26;
    $str =~ s/([a-z])/chr((ord($1) - ord('a') + $shift) % 26 + ord('a'))/ge;
    $str =~ s/([A-Z])/chr((ord($1) - ord('A') + $shift) % 26 + ord('A'))/ge;
    return $str;
}
Python Implementation
def encrypt_string(text: str, shift: int) -> str:
    """Encrypt string by shifting letters by N positions."""
    shift %= 26
    result = []
    for char in text:
        if char.isalpha():
            base = ord('a') if char.islower() else ord('A')
            new_char = chr((ord(char) - base + shift) % 26 + base)
            result.append(new_char)
        else:
            result.append(char)
    return "".join(result)