The weekly challenge 341 - Task 1: Broken Keyboard
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-341/#TASK1 3 # 4 # Task 1: Broken Keyboard 5 # ======================= 6 # 7 # You are given a string containing English letters only and also you are given 8 # broken keys. 9 # 10 # Write a script to return the total words in the given sentence can be typed 11 # completely. 12 # 13 ## Example 1 14 ## 15 ## Input: $str = 'Hello World', @keys = ('d') 16 ## Output: 1 17 ## 18 ## With broken key 'd', we can only type the word 'Hello'. 19 # 20 # 21 ## Example 2 22 ## 23 ## Input: $str = 'apple banana cherry', @keys = ('a', 'e') 24 ## Output: 0 25 # 26 # 27 ## Example 3 28 ## 29 ## Input: $str = 'Coding is fun', @keys = () 30 ## Output: 3 31 ## 32 ## No keys broken. 33 # 34 # 35 ## Example 4 36 ## 37 ## Input: $str = 'The Weekly Challenge', @keys = ('a','b') 38 ## Output: 2 39 # 40 # 41 ## Example 5 42 ## 43 ## Input: $str = 'Perl and Python', @keys = ('p') 44 ## Output: 1 45 # 46 ############################################################ 47 ## 48 ## discussion 49 ## 50 ############################################################ 51 # 52 # Create a list of the words in $str. Then for each of the words, 53 # check if any of the characters in the word is a broken key, we remove 54 # it from the list. Count the remaining words as the result 55 56 use v5.36; 57 58 59 broken_keyboard('Hello World', 'd'); 60 broken_keyboard('apple banana cherry', 'a', 'e'); 61 broken_keyboard('Coding is fun' ); 62 broken_keyboard('The Weekly Challenge', 'a','b'); 63 broken_keyboard('Perl and Python', 'p'); 64 65 sub broken_keyboard($str, @keys) { 66 say "Input: '$str', (" . join(", ", @keys) . ")"; 67 my @words = split /\s+/, $str; 68 my $count = scalar(@words); 69 OUTER: 70 foreach my $w (@words) { 71 foreach my $key (@keys) { 72 if($w =~ m/$key/i) { 73 $count--; 74 next OUTER; 75 } 76 } 77 } 78 say "Output: $count"; 79 }