The Weekly Challenge 378

Second Largest Digit and Sum of Words

Task 1: Second Largest Digit

You are given an alphanumeric string. Write a script to find the second largest distinct digit in the given string. Return -1 if none found.

Example Output

Input: $str = "9zero8eight7seven9" Output: 8 Input: $str = "4abc4def2ghi8jkl2" Output: 4

Logic

Extract all numerical digits from the alphanumeric string. Filter the list to get only unique values to handle duplicates. Sort these unique digits in descending order. If there are at least two unique digits, return the second largest. Otherwise, return -1.

Perl Solution

ch-1.pl

sub second_largest_digit ($str) { my @digits = $str =~ /(\d)/g; my %seen; my @unique_digits = sort { $b <=> $a } grep { !$seen{$_}++ } @digits; if (scalar @unique_digits >= 2) { return int($unique_digits[1]); } return -1; }

Python Solution

ch-1.py

def second_largest_digit(s: str) -> int: digits = [int(char) for char in s if char.isdigit()] unique_digits = sorted(list(set(digits)), reverse=True) if len(unique_digits) >= 2: return unique_digits[1] return -1

Task 2: Sum of Words

You are given three strings consisting of lower case English letters 'a' to 'j' only. The letter value of a = 0, b = 1, c = 2, d = 3, etc. Write a script to find if sum of first two strings return the third string.

Example Output

Input: $str1 = "acb", $str2 = "cba", $str3 = "cdb" Output: true (021 + 210 = 231) Input: $str1 = "bc", $str2 = "je", $str3 = "jg" Output: false (12 + 94 != 96)

Logic

Convert each character of the strings to its numerical digit representation (where 'a' maps to 0, 'b' to 1, ..., 'j' to 9). Concatenate these digits to form a number for each word. Finally, check if the sum of the first two numbers equals the third.

Perl Solution

ch-2.pl

sub word_to_num ($word) { my $num_str = ""; for my $char (split //, $word) { $num_str .= ord($char) - ord('a'); } return int($num_str); } sub sum_of_words ($str1, $str2, $str3) { my $n1 = word_to_num($str1); my $n2 = word_to_num($str2); my $n3 = word_to_num($str3); return ($n1 + $n2 == $n3) ? 1 : 0; }

Python Solution

ch-2.py

def word_to_num(word: str) -> int: num_str = "".join(str(ord(char) - ord("a")) for char in word) return int(num_str) def sum_of_words(str1: str, str2: str, str3: str) -> bool: return word_to_num(str1) + word_to_num(str2) == word_to_num(str3)