perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 315 - Task 2: Find Third

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-315/#TASK2
 3 #
 4 # Task 2: Find Third
 5 # ==================
 6 #
 7 # You are given a sentence and two words.
 8 #
 9 # Write a script to return all words in the given sentence that appear in
10 # sequence to the given two words.
11 #
12 ## Example 1
13 ##
14 ## Input: $sentence = "Perl is a my favourite language but Python is my favourite too."
15 ##        $first = "my"
16 ##        $second = "favourite"
17 ## Output: ("language", "too")
18 #
19 #
20 ## Example 2
21 ##
22 ## Input: $sentence = "Barbie is a beautiful doll also also a beautiful princess."
23 ##        $first = "a"
24 ##        $second = "beautiful"
25 ## Output: ("doll", "princess")
26 #
27 #
28 ## Example 3
29 ##
30 ## Input: $sentence = "we will we will rock you rock you.",
31 ##        $first = "we"
32 ##        $second = "will"
33 ## Output: ("we", "rock")
34 #
35 ############################################################
36 ##
37 ## discussion
38 ##
39 ############################################################
40 #
41 # Remove punctuation from the sentence, then split it into words.
42 # Now for each index, if the word at the index matches $first and
43 # the word after it matches $second, then the word after that will
44 # be added to the result array.
45 
46 use v5.36;
47 
48 find_third("Perl is a my favourite language but Python is my favourite too.", "my", "favourite");
49 find_third("Barbie is a beautiful doll also also a beautiful princess.", "a", "beautiful");
50 find_third("we will we will rock you rock you.", "we", "will");
51 
52 sub find_third($sentence, $first, $second) {
53     say "Input: \$sentence = \"$sentence\"";
54     say "       \$first    = \"$first\"";
55     say "       \$second   = \"$second\"";
56     my @output = ();
57     $sentence =~ s/[,\?\.!]//g; # remove punctuation
58     my @sentence = split /\s+/, $sentence;
59     foreach my $i (0..$#sentence) {
60         if($sentence[$i] eq $first and defined($sentence[$i+1]) and $sentence[$i+1] eq $second) {
61             push @output, $sentence[$i+2] if defined($sentence[$i+2]);
62         }
63     }
64     if(@output) {
65         say "Output: (\"" . join("\", \"", @output) . "\")";
66     } else {
67         say "Output: ()";
68     }
69 }