The Bear's Den

Enter at your own risk

The Third Index

Task 1: Find Words

Submitted by: Mohammad Sajid Anwar


You are given a list of words and a character.

Write a script to return the index of word in the list where you find the given character.

Example 1

Input: @list = ("the", "weekly", "challenge")
       $char = "e"
Output: (0, 1, 2)

Example 2

Input: @list = ("perl", "raku", "python")
       $char = "p"
Output: (0, 2)

Example 3

Input: @list = ("abc", "def", "bbb", "bcd")
       $char = "b"
Output: (0, 2, 3)

Solution

Using a regex to search for the given character extends the solution to finding substrings.

use strict;
use warnings;
use List::MoreUtils 'indexes';

sub find_words {
    my $c = shift;
    indexes {/\Q$c\E/} @_;
}

See the full solution to task 1.

Task 2: Find Third

Submitted by: Mohammad Sajid Anwar


You are given a sentence and two words.

Write a script to return all words in the given sentence that appear in sequence to the given two words.

Example 1

Input: $sentence = "Perl is a my favourite language but Python is my favourite too."
       $first = "my"
       $second = "favourite"
Output: ("language", "too")

Example 2

Input: $sentence = "Barbie is a beautiful doll also also a beautiful princess."
       $first = "a"
       $second = "beautiful"
Output: ("doll", "princess")

Example 3

Input: $sentence = "we will we will rock you rock you.",
       $first = "we"
       $second = "will"
Output: ("we", "rock")

Solution

Some assumptions:

use v5.30;
use warnings;
use experimental qw(signatures vlb);

sub find_third ($first, $second, $sentence) {
    $sentence =~ /(?<=(?:^|\W)$first $second )(\w+)/g;
}

See the full solution to task 2.


If you have a question about this post or if you like to comment on it, feel free to open an issue in my github repository.