The Weekly Challenge - 275


TASK #1: Broken Keys
You are given a sentence, $sentence and list of broken keys @keys.
Write a script to find out how many words can be typed fully.

#!/usr/bin/perl
use strict;
use warnings;

sub broken_keys {
	
    my ($regex) = "[@_[1 .. $#_]]";
    print( scalar( grep { ! /$regex/i } split(/ /, @_[0]) ), "\n" );
    # @_[0] is aesthetically pleasing, scalar(@_[0]) is more precise, but normally 
    # you should use $_[0]
    
}

# Tests

my ($sentence, @keys);

# Example 1
$sentence = "Perl Weekly Challenge";
@keys = ('l', 'a'); 
broken_keys($sentence, @keys); # Output: 0

# Example 2
$sentence = "Perl and Raku"; 
@keys = ('a');
broken_keys($sentence, @keys); # Output: 1

# Example 3
$sentence = "Well done Team PWC";
@keys = ('l', 'o'); 
broken_keys($sentence, @keys); # Output: 2

# Example 4
$sentence = "The joys of polyglottism";
@keys = ('T');
broken_keys($sentence, @keys); # Output: 2

TASK #2: Replace Digits
You are given an alphanumeric string, $str, where each character is either a letter or a digit.
Write a script to replace each digit in the given string with the value of the previous letter plus (digit) places.
#!/usr/bin/perl
use strict;
use warnings;

sub replace_digits {
	
    my ($result, $prev_char);
        
    foreach my $char (split(//, $_[0])) {
      
        ($char =~ /[a-z]/i) ? ( $result .= $prev_char = $char ) 
                            : ( $result .= chr( ord($prev_char) + $char ) );
    
    }
    print ($result, "\n");
}

# Tests

my $str;

# Example 1
$str = "a1c1e1";
replace_digits($str); # Output: 'abcdef'

# Example 2
$str = "a1b2c3d4";
replace_digits($str); # Output: 'abbdcfdh'

# Example 3
$str = "b2b";
replace_digits($str); # Output: 'bdb'

# Example 4
$str = "a16z";
replace_digits($str); # Output: 'abgz'

# Example 5
$str = "a1234f";
replace_digits($str); # Output: 'abcdef'

# Example 6
$str = "A1234F";
replace_digits($str); # Output: 'ABCDEF'

#Example 7 (test example from Niels van Dijke)
$str = "Z5";
replace_digits($str); # Output: 'Z_'