Robbie Hatley’s Solutions, in Perl, for The Weekly Challenge #366 (“Count Prefixes” and “Valid Times”)
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 2026-03-23 through 2026-03-29 is #366. The tasks for challenge #366 are as follows:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task 366-1: Count Prefixes Submitted by: Mohammad Sajid Anwar You are given an array of words and a string (contains only lowercase English letters). Write a script to return the number of words in the given array that are a prefix of the given string. ( # Example #1 input: [["a", "ap", "app", "apple", "banana"], "apple"], # Expected output: 4 # Example #2 input: [["cat", "dog", "fish"], "bird"], # Expected output: 0 # Example #3 input: [["hello", "he", "hell", "heaven", "he"], "hello"], # Expected output: 4 # Example 4 input: [["", "code", "coding", "cod"], "coding"], # Expected output: 3 # Example #5 input: [["p", "pr", "pro", "prog", "progr", "progra", "program"], "program"], # Expected output: 7 );
My first approach was this: Given array-of-candidate-words "@array" and string "$string", I incremented a zero-initialized counter "$pcount" for each "$candidate" within "@array" for which $string =~ m/^$candidate/. I then returned that counter.
But while that does work, I realized there is a better approach: use "grep" in scalar context to count number of candidates "$candidate" within "@array" which match "/^$candidate/".
Robbie Hatley's Perl Solution to The Weekly Challenge 366-1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task 366-2: Valid Times Submitted by: Mohammad Sajid Anwar You are given a time in the form ‘HH:MM’. The earliest possible time is ‘00:00’ and the latest possible time is ‘23:59’. In the string time, the digits represented by the ‘?’ symbol are unknown, and must be replaced with a digit from 0 to 9. Write a script to return the count different ways we can make it a valid time. Example 1 Input: $time = "?2:34" Output: 3 Example 2 Input: $time = "?4:?0" Output: 12 Example 3 Input: $time = "??:??" Output: 1440 Example 4 Input: $time = "?3:45" Output: 3 Example 5 Input: $time = "2?:15" Output: 4
I'll write two subs: One to assure that the string itself is valid, and second to determine how many valid times can be made from the input string.
Robbie Hatley's Perl Solution to The Weekly Challenge 366-2
That's it for challenge 366; see you on challenge 367!
Comments
Post a Comment