Prefixes and times?
Weekly challenge 366 — 23 March 2026
Week 366: 23 Mar 2026
You are given an array of words and a string which 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: @array = ('a', 'ap', 'app', 'apple', 'banana'), $str = 'apple' Output: 4 Example 2 Input: @array = ('cat', 'dog', 'fish'), $str = 'bird' Output: 0 Example 3 Input: @array = ('hello', 'he', 'hell', 'heaven', 'he'), $str = 'hello' Output: 4 Example 4 Input: @array = ('', 'code', 'coding', 'cod'), $str = 'coding' Output: 3 Example 5 Input: @array = ('p', 'pr', 'pro', 'prog', 'progr', 'progra', 'program'), $str = 'program' Output: 7
This is an easy one for Prel, the answer being:
grep { $string =~ m|^$_| } @words
The expression in curly brackets tests whether each
word (mapped to $_) is or isn't a prefix of $string.
It returns a list of those that are, or, as it's assigned
to a scalar, a count of such words.
And that's the answer we want.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2026-03-23 use utf8; # Week 366 - task 1 - Count prefixes use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; count_prefixes(['a', 'ap', 'app', 'apple', 'banana'], 'apple'); count_prefixes(['cat', 'dog', 'fish'], 'bird'); count_prefixes(['hello', 'he', 'hell', 'heaven', 'he'], 'hello'); count_prefixes(['', 'code', 'coding', 'cod'], 'coding'); count_prefixes(['p', 'pr', 'pro', 'prog', 'progr', 'progra', 'program'], 'program'); sub count_prefixes { my (@words, $string); # initialise @words = @{$_[0]}; $string = $_[1]; # report say qq[\nInput: \$words = ('] . join(q[', '], @words) . qq['), \$string = '$string']; say qq[Output: ] . grep { $string =~ m|^$_| } @words; }
last updated 2026-03-23 — 7 lines of code
Input: $words = ('a', 'ap', 'app', 'apple', 'banana'), $string = 'apple' Output: 4 Input: $words = ('cat', 'dog', 'fish'), $string = 'bird' Output: 0 Input: $words = ('hello', 'he', 'hell', 'heaven', 'he'), $string = 'hello' Output: 4 Input: $words = ('', 'code', 'coding', 'cod'), $string = 'coding' Output: 3 Input: $words = ('p', 'pr', 'pro', 'prog', 'progr', 'progra', 'program'), $string = 'program' Output: 7
Any content of this website which has been created by Peter Campbell Smith is in the public domain