perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 366 - Task 1: Count Prefixes

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-366/#TASK1
 3 #
 4 # Task 1: Count Prefixes
 5 # ======================
 6 #
 7 # You are given an array of words and a string (contains only lowercase English
 8 # letters).
 9 #
10 # Write a script to return the number of words in the given array that are a
11 # prefix of the given string.
12 #
13 ## Example 1
14 ##
15 ## Input: @array = ("a", "ap", "app", "apple", "banana"), $str = "apple"
16 ## Output: 4
17 #
18 ## Example 2
19 ##
20 ## Input: @array = ("cat", "dog", "fish"), $str = "bird"
21 ## Output: 0
22 #
23 ## Example 3
24 ##
25 ## Input: @array = ("hello", "he", "hell", "heaven", "he"), $str = "hello"
26 ## Output: 4
27 #
28 ## Example 4
29 ##
30 ## Input: @array = ("", "code", "coding", "cod"), $str = "coding"
31 ## Output: 3
32 #
33 ## Example 5
34 ##
35 ## Input: @array = ("p", "pr", "pro", "prog", "progr", "progra", "program"), $str = "program"
36 ## Output: 7
37 #
38 ############################################################
39 ##
40 ## discussion
41 ##
42 ############################################################
43 #
44 # We simply count the elements of the array that are prefixes of the string.
45 
46 use v5.36;
47 
48 count_prefixes(["a", "ap", "app", "apple", "banana"], "apple");
49 count_prefixes(["cat", "dog", "fish"], "bird");
50 count_prefixes(["hello", "he", "hell", "heaven", "he"], "hello");
51 count_prefixes(["", "code", "coding", "cod"], "coding");
52 count_prefixes(["p", "pr", "pro", "prog", "progr", "progra", "program"], "program");
53 
54 sub count_prefixes($array, $str) {
55     say "Input: (\"" . join("\", \"", @$array) . "\")", "\"$str\"";
56     my $count = 0;
57     foreach my $elem (@$array) {
58         $count++ if $str =~ m/^$elem/;
59     }
60     say "Output: $count";
61 }