Task 1: Last Word
Find the last word matching a given regex pattern in a string.
Example Output
Input: 'hello world', Pattern: /el/
Output: 'hello'
Logic
Extract all whitespace-delimited words in the string and iterate backwards to find the last word matching the regex.
Perl Solution
ch-1.pl
sub last_word {
my ($string, $regexp) = @_;
my @words = $string =~ /(\S+)/g;
for my $word (reverse @words) {
return $word if $word =~ $regexp;
}
return undef;
}
Python Solution
ch-1.py
def last_word(string: str, pattern: str):
words = string.split()
for word in reversed(words):
if re.search(pattern, word):
return word
return None
Task 2: Minimum Rotations
Find the minimum number of non-zero left rotations needed for string S to equal its original form.
Example Output
Input: 'xyxx'
Output: Minimum rotations: 7
Logic
Repeatedly rotate the string left character by character until the string matches the original starting string.
Perl Solution
ch-2.pl
sub min_rotations {
my ($word) = @_;
my $current = $word;
my $count = 0;
do {
$current = substr($current, 1) . substr($current, 0, 1);
$count++;
} while ($current ne $word);
return $count;
}
Python Solution
ch-2.py
def min_rotations(word: str) -> int:
current = word
count = 0
while True:
current = current[1:] + current[0]
count += 1
if current == word:
return count