All about characters
Weekly challenge 273 — 10 June 2024
Week 273: 10 Jun 2024
You are given a string, $str
. Write a script to return true
if there is at least one
b
, and no a
appears after the first b
.
Example 1 Input: $str = "aabb" Output: true Example 2 Input: $str = "abab" Output: false Example 3 Input: $str = "aaa" Output: false Example 4 Input: $str = "bbb" Output: true
This is an easy one-liner:
($str =~ m|b(.*)| and $1 =~ m|^[^a]*$|) ? 'true' : 'false'
The first regular expression - $str =~ m|b(.*)|
- looks for a 'b' and
the second - $1 =~ m|^[^a]*$|
- checks for no 'a' in the part of the string follwing the first 'b':
note that the $1 refers to the matched substring from the first regular expression.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2024-06-10 use utf8; # Week 273 - task 2 - B after a use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; b_after_a('aabb'); b_after_a('abab'); b_after_a('aaa'); b_after_a('bbb'); b_after_a('ccc'); b_after_a('Write a script to return true if there is at least one b'); sub b_after_a { my $str = $_[0]; # match a 'b', and then match no 'a' in the rest of the string say qq[\nInput: \$str = '$str']; say qq[Output: ] . (($str =~ m|b(.*)| and $1 =~ m|^[^a]*$|) ? 'true' : 'false'); }
Input: $str = 'aabb' Output: true Input: $str = 'abab' Output: false Input: $str = 'aaa' Output: false Input: $str = 'bbb' Output: true Input: $str = 'ccc' Output: false Input: $str = 'Write a script to return true if there is at least one b' Output: true
Any content of this website which has been created by Peter Campbell Smith is in the public domain