The weekly challenge 273 - Task 2: B After A
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-273/#TASK2 3 # 4 # Task 2: B After A 5 # ================= 6 # 7 # You are given a string, $str. 8 # 9 # Write a script to return true if there is at least one b, and no a appears 10 # after the first b. 11 # 12 ## Example 1 13 ## 14 ## Input: $str = "aabb" 15 ## Output: true 16 # 17 ## Example 2 18 ## 19 ## Input: $str = "abab" 20 ## Output: false 21 # 22 ## Example 3 23 ## 24 ## Input: $str = "aaa" 25 ## Output: false 26 # 27 ## Example 4 28 ## 29 ## Input: $str = "bbb" 30 ## Output: true 31 # 32 ############################################################ 33 ## 34 ## discussion 35 ## 36 ############################################################ 37 # 38 # We walk the string character for character. If we find a "b" 39 # we remember this fact. If we encounter an "a" and have already 40 # seen a "b", we return false. If we're at the end of the string 41 # our output depends on whether or not we have seen a "b": we 42 # didn't bail out for seeing an "a" after a "b", so if we didn't 43 # see any "b" at all, we return false, otherwise true. 44 45 use strict; 46 use warnings; 47 48 b_after_a("aabb"); 49 b_after_a("abab"); 50 b_after_a("aaa"); 51 b_after_a("bbb"); 52 53 sub b_after_a { 54 my $str = shift; 55 print "Input: '$str'\n"; 56 my $b_seen = 0; 57 foreach my $char (split //, $str) { 58 $b_seen = 1 if $char eq "b"; 59 if($b_seen) { 60 return print "Output: false\n" if $char eq "a"; 61 } 62 } 63 if($b_seen) { 64 print "Output: true\n"; 65 } else { 66 print "Output: false\n"; 67 } 68 }