Broken keys and
mixed up words
Weekly challenge 341 — 29 September 2025
Week 341: 29 Sep 2025
You are given a string containing only English letters and a list of broken keys - letters that cannot be typed. Write a script to return the total words in the given sentence that can be typed completely.
Example 1 Input: $str = 'Hello World', @keys = ('d') Output: 1 With broken key 'd', we can only type the word 'Hello'. Example 2 Input: $str = 'apple banana cherry', @keys = ('a', 'e') Output: 0 Example 3 Input: $str = 'Coding is fun', @keys = () Output: 3 No keys broken. Example 4 Input: $str = 'The Weekly Challenge', @keys = ('a','b') Output: 2 Example 5 Input: $str = 'Perl and Python', @keys = ('p') Output: 1
My algorithm is:
$keys
(eg 'abc')
\w*[$keys]\w*
and delete them
The regex deletes an occurrence of zero or more letters
followed by a broken key followed by zero
or more letters. The g
modifier repeats that until
there are no more matches. It doesn't matter if the word
contains more than one broken key: as soon as the first
one is detected, the whole word is deleted.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2025-09-29 use utf8; # Week 341 - task 1 - Broken keyboard use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; broken_keyboard('Hello world', ['d']); broken_keyboard('apple banana cherry', ['a', 'e']); broken_keyboard('Coding is fun', []); broken_keyboard('Perl and Python', ['p']); broken_keyboard('aaaaa ccc b', ['a', 'b']); sub broken_keyboard { my ($string, $keys, $count); # initialise and concatenate broken keys no warnings 'uninitialized'; $string = $_[0]; $keys .= $_ for @{$_[1]}; # delete words containing broken keys $string =~ s|\w*[$keys]\w*||gi if $keys; # count the remaining words $count ++ while $string =~ m|\w+|gi; # report say qq[\nInput: \$string = '$_[0]', \@keys = ('] . join(q[', '], @{$_[1]}) . q[')]; say qq[Output: ] . ($count + 0); }
Input: $string = 'Hello world', @keys = ('d') Output: 1 Input: $string = 'apple banana cherry', @keys = ('a', 'e') Output: 0 Input: $string = 'Coding is fun', @keys = ('') Output: 3 Input: $string = 'Perl and Python', @keys = ('p') Output: 1 Input: $string = 'aaaaa ccc b', @keys = ('a', 'b') Output: 1
Any content of this website which has been created by Peter Campbell Smith is in the public domain