The weekly challenge 378 - Task 1: Second Largest Digit
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-378/#TASK1 3 # 4 # Task 1: Second Largest Digit 5 # ============================ 6 # 7 # You are given an alphanumeric string. 8 # 9 # Write a script to find the second largest distinct digit in the given string. 10 # Return -1 if none found. 11 # 12 ## Example 1 13 ## 14 ## Input: $str = "aaaaa77777" 15 ## Output: -1 16 ## 17 ## The only digit in the given string is 7 and there is no second digit. 18 # 19 ## Example 2 20 ## 21 ## Input: $str = "abcde" 22 ## Output: -1 23 ## 24 ## No numerical digits in the given string. 25 # 26 ## Example 3 27 ## 28 ## Input: $str = "9zero8eight7seven9" 29 ## Output: 8 30 # 31 ## Example 4 32 ## 33 ## Input: $str = "xyz9876543210" 34 ## Output: 8 35 # 36 ## Example 5 37 ## 38 ## Input: $str = "4abc4def2ghi8jkl2" 39 ## Output: 4 40 # 41 ############################################################ 42 ## 43 ## discussion 44 ## 45 ############################################################ 46 # 47 # We collect all found digits in a hash, then use that to create 48 # a sorted array from those found digits to fill then into an array. 49 # Then we pick the second element from that array, but only if there 50 # are enough. Otherwise, we fail with a return of "-1". 51 52 use v5.36; 53 54 second_largest_digit("aaaaa77777"); 55 second_largest_digit("abcde"); 56 second_largest_digit("9zero8eight7seven9"); 57 second_largest_digit("xyz9876543210"); 58 second_largest_digit("4abc4def2ghi8jkl2"); 59 60 sub second_largest_digit($str) { 61 say "Input: \"$str\""; 62 my $digits = {}; 63 foreach my $c (split //, $str) { 64 next unless $c =~ m/\d/; 65 $digits->{$c} = 1; 66 } 67 my @found_digits = sort { $b <=> $a } keys %$digits; 68 if ( scalar(@found_digits) < 2 ) { 69 say "Output: -1"; 70 } else { 71 say "Output: $found_digits[1]"; 72 } 73 }