Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #341 (“Broken Keyboard” and “Reverse Prefix”)
For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle with two parts, with a new pair of tasks each Monday. You can find it here: The Weekly Challenge
The Weekly Challenge for the week of 2025-09-29 through 2025-10-05 is #341. The tasks for challenge #341 are as follows:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task 341-1: Broken Keyboard Submitted by: Mohammad Sajid Anwar You are given a string containing English letters only, and you are given a list of broken keys. Write a script to return the total words in the given sentence can be typed completely. Example #1 input: $str = 'Hello World', @keys = ('d') Expected output: 1 Example #2 input: $str = 'apple banana cherry', @keys = ('a', 'e') Expected output: 0 Example #3 input: $str = 'Coding is fun', @keys = () Expected output: 3 Example #4 input: $str = 'The Weekly Challenge', @keys = ('a','b') Expected output: 2 Example #5 input: $str = 'Perl and Python', @keys = ('p') Expected output: 1
I'll join each "broken key" character and its "shift" (the other character using the same key) into a string
"$forbidden", then interpolate $forbidden into a regular-expression character class, then case-insensitively
match incoming words against that regexp and push non-matching words to array @allowed, like so:
for (@words) {if ($_ !~ m/[\Q$forbidden\E]/i) {push @allowed, $_}}
I'll then return the scalar of @allowed.

Robbie Hatley's Perl Solution to The Weekly Challenge 341-1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task 341-2: Reverse Prefix Submitted by: Mohammad Sajid Anwar You are given a string $s and a character $c in $s. Write a script to reverse the prefix up-to-and-including the first occurrence of $c in $s and return the new string. Example #1 input: $s = "programming", $c = "g" Expected output: "gorpramming" Example #2 input: $s = "hello", $c = "h" Expected output: "hello" Example #3 input: $s = "abcdefghij", $c = "h" Expected output: "hgfedcbaij" Example #4 input: $s = "reverse", $c = "s" Expected output: "srevere" Example #5 input: $s = "perl", $c = "r" Expected output: "repl"
To solve this problem, I'll use the little-known scalar version of Perl's built-in "reverse" function,
in combination with a "minimal-zero-or-more" regular expression in an "s///re" version of the "s///"
substitution operator, like so:
"$s =~ s/^(.*?$c)/reverse($1)/er".

Robbie Hatley's Perl Solution to The Weekly Challenge 341-2
That's it for challenge 341; see you on challenge 342!
Comments
Post a Comment