The weekly challenge 328 - Task 1: Replace all ?
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-328/#TASK1 3 # 4 # Task 1: Replace all ? 5 # ===================== 6 # 7 # You are given a string containing only lower case English letters and ?. 8 # 9 # Write a script to replace all ? in the given string so that the string 10 # doesn’t contain consecutive repeating characters. 11 # 12 ## Example 1 13 ## 14 ## Input: $str = "a?z" 15 ## Output: "abz" 16 ## 17 ## There can be many strings, one of them is "abz". 18 ## The choices are 'a' to 'z' but we can't use either 'a' or 'z' to replace the '?'. 19 # 20 # 21 ## Example 2 22 ## 23 ## Input: $str = "pe?k" 24 ## Output: "peak" 25 # 26 # 27 ## Example 3 28 ## 29 ## Input: $str = "gra?te" 30 ## Output: "grabte" 31 # 32 ############################################################ 33 ## 34 ## discsussion 35 ## 36 ############################################################ 37 # 38 # Starting from left to right, we pick each "?" and try to replace it. 39 # For that, we walk the characters from a to z, and if we find one that 40 # works, we use it right away. 41 42 use v5.36; 43 44 replace_all("a?z"); 45 replace_all("pe?k"); 46 replace_all("gra?te"); 47 replace_all("gra?te"); 48 replace_all("?bc"); 49 replace_all("ab?"); 50 replace_all("ab?a"); 51 replace_all("ab???"); 52 replace_all("???a"); 53 54 sub replace_all($str) { 55 say "Input: $str"; 56 my @chars = split //, $str; 57 foreach my $i (0..$#chars) { 58 if($chars[$i] eq "?") { 59 foreach my $c ("a".."z") { 60 my $ok = 1; 61 if($i != 0) { 62 if($chars[$i-1] eq $c) { 63 $ok = 0; 64 } 65 } 66 if($i != $#chars) { 67 if($chars[$i+1] eq $c) { 68 $ok = 0; 69 } 70 } 71 if($ok) { 72 $chars[$i] = $c; 73 last; 74 } 75 } 76 } 77 } 78 my $output = join("",@chars); 79 say "Output: $output"; 80 }