The weekly challenge 364 - Task 1: Decrypt String
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-364/#TASK1 3 # 4 # Task 1: Decrypt String 5 # ====================== 6 # 7 # You are given a string formed by digits and ‘#'. 8 # 9 # Write a script to map the given string to English lowercase characters 10 # following the given rules. 11 # 12 ## - Characters 'a' to 'i' are represented by '1' to '9' respectively. 13 ## - Characters 'j' to 'z' are represented by '10#' to '26#' respectively. 14 # 15 ## Example 1 16 ## 17 ## Input: $str = "10#11#12" 18 ## Output: "jkab" 19 ## 20 ## 10# -> j 21 ## 11# -> k 22 ## 1 -> a 23 ## 2 -> b 24 # 25 ## Example 2 26 ## 27 ## Input: $str = "1326#" 28 ## Output: "acz" 29 ## 30 ## 1 -> a 31 ## 3 -> c 32 ## 26# -> z 33 # 34 ## Example 3 35 ## 36 ## Input: $str = "25#24#123" 37 ## Output: "yxabc" 38 ## 39 ## 25# -> y 40 ## 24# -> x 41 ## 1 -> a 42 ## 2 -> b 43 ## 3 -> c 44 # 45 ## Example 4 46 ## 47 ## Input: $str = "20#5" 48 ## Output: "te" 49 ## 50 ## 20# -> t 51 ## 5 -> e 52 # 53 ## Example 5 54 ## 55 ## Input: $str = "1910#26#" 56 ## Output: "aijz" 57 ## 58 ## 1 -> a 59 ## 9 -> i 60 ## 10# -> j 61 ## 26# -> z 62 # 63 ############################################################ 64 ## 65 ## discussion 66 ## 67 ############################################################ 68 # 69 # As long as we have two digits in front of a "#" at the beginning 70 # of $str, we pick those two digits, add 96 and call chr() on the 71 # result (because "a" is ASCII 97 and we start counting at 1). If 72 # $str doesn't start in two digits and "#", then we pick the first 73 # digits, add 96 and hand the result to chr(). We do that until 74 # there is nothing left in $str. 75 76 use v5.36; 77 78 decrypt_string("10#11#12"); 79 decrypt_string("1326#"); 80 decrypt_string("25#24#123"); 81 decrypt_string("20#5"); 82 decrypt_string("1910#26#"); 83 84 sub decrypt_string($str) { 85 say "Input: \"$str\""; 86 my $result = ""; 87 while(length($str)) { 88 if($str =~ m/(^\d\d)#/) { 89 $result .= chr(96+$1); 90 $str =~ s/...//; 91 } else { 92 $result .= chr(96+ substr($str,0,1,"")); 93 } 94 } 95 say "Output: \"$result\""; 96 }