The weekly challenge 275 - Task 2: Replace Digits
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-275/#TASK2 3 # 4 # Task 2: Replace Digits 5 # ====================== 6 # 7 # You are given an alphanumeric string, $str, where each character is either a 8 # letter or a digit. 9 # 10 # Write a script to replace each digit in the given string with the value of 11 # the previous letter plus (digit) places. 12 # 13 ## Example 1 14 ## 15 ## Input: $str = 'a1c1e1' 16 ## Ouput: 'abcdef' 17 ## 18 ## shift('a', 1) => 'b' 19 ## shift('c', 1) => 'd' 20 ## shift('e', 1) => 'f' 21 # 22 ## Example 2 23 ## 24 ## Input: $str = 'a1b2c3d4' 25 ## Output: 'abbdcfdh' 26 ## 27 ## shift('a', 1) => 'b' 28 ## shift('b', 2) => 'd' 29 ## shift('c', 3) => 'f' 30 ## shift('d', 4) => 'h' 31 # 32 ## Example 3 33 ## 34 ## Input: $str = 'b2b' 35 ## Output: 'bdb' 36 # 37 ## Example 4 38 ## 39 ## Input: $str = 'a16z' 40 ## Output: 'abgz' 41 # 42 ############################################################ 43 ## 44 ## discussion 45 ## 46 ############################################################ 47 # 48 # Walk the $str character by character. If it is a digits, 49 # calculate the corresponding new character for the result by 50 # using the previous character and the digit, otherwise just 51 # append the current character and take note of the character 52 # for the next round. 53 54 use strict; 55 use warnings; 56 57 replace_digits('a1c1e1'); 58 replace_digits('a1b2c3d4'); 59 replace_digits('b2b'); 60 replace_digits('a16z'); 61 62 sub replace_digits { 63 my $str = shift; 64 print "Input: '$str'\n"; 65 my $previous_char = "a"; 66 my $result = ""; 67 foreach my $char (split //, $str) { 68 if($char =~ m/\d/) { 69 $result .= chr(ord($previous_char) + $char); 70 } else { 71 $result .= $char; 72 $previous_char = $char; 73 } 74 } 75 print "Output: '$result'\n"; 76 }