Robbie Hatley's Solutions To The Weekly Challenge #273

For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle with two parts, cycling every Sunday. You can find it here:

The Weekly Challenge

The Weekly Challenge for the week of 2024-06-09 through 2024-06-15 is #273. Its tasks are as follows:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 273-1: Percentage of Character
Submitted by: Mohammad Sajid Anwar
You are given a string, $str and a character $chr. Write a
script to return the nearest integer percentage of the
characters in $str which are $chr.

Example 1:
Input: $str = "perl", $chr = "e"
Output: 25

Example 2:
Input: $str = "java", $chr = "a"
Output: 50

Example 3:
Input: $str = "python", $chr = "m"
Output: 0

Example 4:
Input: $str = "ada", $chr = "a"
Output: 67

Example 5:
Input: $str = "ballerina", $chr = "l"
Output: 22

Example 6:
Input: $str = "analitik", $chr = "k"
Output: 13

This is just a matter of counting instances of $chr in $str, dividing by length($str), multiplying by 100, and rounding to nearest integer. The m// operator and the "lround" function from POSIX are useful here:

"vowel"     = one of [aeiou] and case variants, with or without combining marks.
              (eg: ÅËiòU)
"consonant" = any character which is not a "vowel".
              (eg: b7$@ÐgÑ茶z)
"word"      = any cluster of non-horizontal-whitespace characters.
              (eg: "79.m:v", "du#f", "$17")
"sentence"  = any string consisting of "words" separated by horizontal whitespace.
              (eg: "79.m:v du#f $17")

Robbie Hatley's Perl Solution to The Weekly Challenge 273-1

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 273-2: B After A
Submitted by: Mohammad Sajid Anwar
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

A regular expression will solve this. What we're looking for is "initial b followed by non-a characters to end of string". The regular expression for that is "^[^b]*b[^a]*$":

   sub b_after_a ($str) {
      $str =~ m/^[^b]*b[^a]*$/
   }

Robbie Hatley's Perl Solution to The Weekly Challenge 273-2

That's it for challenge 273; see you on challenge 274!

Comments

Popular posts from this blog

Robbie Hatley's Solutions To The Weekly Challenge #262

Robbie Hatley's Solutions To The Weekly Challenge #266