The weekly challenge 275 - Task 1: Broken Keys

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-275/#TASK1
 3 #
 4 # Task 1: Broken Keys
 5 # ===================
 6 #
 7 # You are given a sentence, $sentence and list of broken keys @keys.
 8 #
 9 # Write a script to find out how many words can be typed fully.
10 #
11 ## Example 1
12 ##
13 ## Input: $sentence = "Perl Weekly Challenge", @keys = ('l', 'a')
14 ## Output: 0
15 #
16 ## Example 2
17 ##
18 ## Input: $sentence = "Perl and Raku", @keys = ('a')
19 ## Output: 1
20 ##
21 ## Only Perl since the other word two words contain 'a' and can't be typed fully.
22 #
23 ## Example 3
24 ##
25 ## Input: $sentence = "Well done Team PWC", @keys = ('l', 'o')
26 ## Output: 2
27 #
28 ## Example 4
29 ##
30 ## Input: $sentence = "The joys of polyglottism", @keys = ('T')
31 ## Output: 2
32 #
33 ############################################################
34 ##
35 ## discussion
36 ##
37 ############################################################
38 #
39 # We split the sentence into its words. Then we create an empty
40 # temporary list, and walk through the list of broken keys. If a
41 # word doesn't match the broken key, it will go into the temporary
42 # list, and at the end of each loop over the broken keys, the new
43 # list will be the list of words from the sentence that didn't
44 # match any broken keys so far, while the temporary list will be
45 # emptied again. This way, at the end of the loop over the broken
46 # keys, we only have the words that don't match any of the broken
47 # keys in the final list, of which we return the number of elements.
48 
49 use strict;
50 use warnings;
51 
52 broken_keys( "Perl Weekly Challenge", "l", "a" );
53 broken_keys( "Perl and Raku", "a" );
54 broken_keys( "Well done Team PWC", "l", "o" );
55 broken_keys( "The joys of polyglottism", "T" );
56 
57 sub broken_keys {
58    my ($sentence, @bk ) = @_;
59    print "Input: \$sentence = '$sentence', ('", join("', '", @bk), "')\n";
60    my @words = split /\s+/, lc($sentence);
61    my @tmp = ();
62    foreach my $broken (@bk) {
63       $broken = lc($broken);
64       foreach my $word (@words) {
65          push @tmp, $word unless $word =~ m/$broken/;
66       }
67       @words = @tmp;
68       @tmp = ();
69    }
70    print "Output: ", scalar(@words), "\n";
71 }
72