The weekly challenge 364 - Task 2: Goal Parser
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-364/#TASK2 3 # 4 # Task 2: Goal Parser 5 # =================== 6 # 7 # You are given a string, $str. 8 # 9 # Write a script to interpret the given string using Goal Parser. 10 # 11 ## The Goal Parser interprets “G” as the string “G”, “()” as the string 12 ## “o”, and “(al)” as the string “al”. The interpreted strings are then 13 ## concatenated in the original order. 14 # 15 ## Example 1 16 ## 17 ## Input: $str = "G()(al)" 18 ## Output: "Goal" 19 ## 20 ## G -> "G" 21 ## () -> "o" 22 ## (al) -> "al" 23 # 24 ## Example 2 25 ## 26 ## Input: $str = "G()()()()(al)" 27 ## Output: "Gooooal" 28 ## 29 ## G -> "G" 30 ## four () -> "oooo" 31 ## (al) -> "al" 32 # 33 ## Example 3 34 ## 35 ## Input: $str = "(al)G(al)()()" 36 ## Output: "alGaloo" 37 ## 38 ## (al) -> "al" 39 ## G -> "G" 40 ## (al) -> "al" 41 ## () -> "o" 42 ## () -> "o" 43 # 44 ## Example 4 45 ## 46 ## Input: $str = "()G()G" 47 ## Output: "oGoG" 48 ## 49 ## () -> "o" 50 ## G -> "G" 51 ## () -> "o" 52 ## G -> "G" 53 # 54 ## Example 5 55 ## 56 ## Input: $str = "(al)(al)G()()" 57 ## Output: "alalGoo" 58 ## 59 ## (al) -> "al" 60 ## (al) -> "al" 61 ## G -> "G" 62 ## () -> "o" 63 ## () -> "o" 64 # 65 ############################################################ 66 ## 67 ## discussion 68 ## 69 ############################################################ 70 # 71 # As long as there are still characters in $str, we remove either 72 # a starting "G", "()" or "(al)", and add a "G", "o" or "al" to 73 # the result. 74 75 use v5.36; 76 77 goal_parser("G()(al)"); 78 goal_parser("G()()()()(al)"); 79 goal_parser("(al)G(al)()()"); 80 goal_parser("()G()G"); 81 goal_parser("(al)(al)G()()"); 82 83 sub goal_parser($str) { 84 say "Input: \"$str\""; 85 my $result = ""; 86 while(length($str)) { 87 if($str =~ m/^G/ ) { 88 $result .= "G"; 89 $str =~ s/^.//; 90 } elsif ($str =~ m/^\(\)/) { 91 $result .= "o"; 92 $str =~ s/^..//; 93 } elsif ($str =~ m/^\(al\)/) { 94 $result .= "al"; 95 $str =~ s/^....//; 96 } else { 97 die "Unrecognized pattern in $str"; 98 } 99 } 100 say "Output: \"$result\""; 101 }