The weekly challenge 358 - Task 1: Max Str Value
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-358/#TASK1 3 # 4 # Task 1: Max Str Value 5 # ===================== 6 # 7 # You are given an array of alphanumeric string, @strings. 8 # 9 # Write a script to find the max value of alphanumeric string in the given 10 # array. The numeric representation of the string, if it comprises of digits 11 # only otherwise length of the string. 12 # 13 ## Example 1 14 ## 15 ## Input: @strings = ("123", "45", "6") 16 ## Output: 123 17 ## 18 ## "123" -> 123 19 ## "45" -> 45 20 ## "6" -> 6 21 # 22 # 23 ## Example 2 24 ## 25 ## Input: @strings = ("abc", "de", "fghi") 26 ## Output: 4 27 ## 28 ## "abc" -> 3 29 ## "de" -> 2 30 ## "fghi" -> 4 31 # 32 # 33 ## Example 3 34 ## 35 ## Input: @strings = ("0012", "99", "a1b2c") 36 ## Output: 99 37 ## 38 ## "0012" -> 12 39 ## "99" -> 99 40 ## "a1b2c" -> 5 41 # 42 # 43 ## Example 4 44 ## 45 ## Input: @strings = ("x", "10", "xyz", "007") 46 ## Output: 10 47 ## 48 ## "x" -> 1 49 ## "xyz" -> 3 50 ## "007" -> 7 51 ## "10" -> 10 52 # 53 # 54 ## Example 5 55 ## 56 ## Input: @strings = ("hello123", "2026", "perl") 57 ## Output: 2026 58 ## 59 ## "hello123" -> 8 60 ## "perl" -> 4 61 ## "2026" -> 2026 62 # 63 ############################################################ 64 ## 65 ## discussion 66 ## 67 ############################################################ 68 # 69 # We calculate the value of each element, then we keep track 70 # of the maximum. 71 72 use v5.36; 73 74 max_str_value("123", "45", "6"); 75 max_str_value("abc", "de", "fghi"); 76 max_str_value("0012", "99", "a1b2c"); 77 max_str_value("x", "10", "xyz", "007"); 78 max_str_value("hello123", "2026", "perl"); 79 80 sub max_str_value(@strings) { 81 say "Input: (\"" . join("\", \"", @strings) . "\")"; 82 my $max; 83 foreach my $elem (@strings) { 84 my $val; 85 if($elem =~ m/^\d+$/) { 86 $val = $elem; 87 } else { 88 $val = length($elem); 89 } 90 $max = $val unless $max; 91 $max = $val if $val > $max; 92 } 93 say "Output: $max"; 94 }