perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 377 - Task 1: Reverse Existence

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-377/#TASK1
 3 #
 4 # Task 1: Reverse Existence
 5 # =========================
 6 #
 7 # You are given a string.
 8 #
 9 # Write a script to find whether any substring of length 2 is also present in
10 # the reverse of the given string.
11 #
12 ## Example 1
13 ##
14 ## Input: $str = "abcba"
15 ## Output: true
16 ##
17 ## Reverse of given string is "abcba".
18 ## The substring "ab" in original string is also present in the reverse string
19 ## too.
20 #
21 ## Example 2
22 ##
23 ## Input: $str = "racecar"
24 ## Output: true
25 ##
26 ## The substring "ce" is present in both.
27 #
28 ## Example 3
29 ##
30 ## Input: $str = "abcd"
31 ## Output: false
32 #
33 ## Example 4
34 ##
35 ## Input: $str = "banana"
36 ## Output: true
37 ##
38 ## The substring "an" is present in both.
39 #
40 ## Example 5
41 ##
42 ## Input: $str = "hello"
43 ## Output: true
44 ##
45 ## The substring "ll" is present in both.
46 #
47 ############################################################
48 ##
49 ## discussion
50 ##
51 ############################################################
52 #
53 # We create the reverse string first. Then we create all
54 # substrings of length 2, and if that substring is in the
55 # reverse string, we can finish execution by returning true.
56 
57 use v5.36;
58 
59 reverse_existence("abcba");
60 reverse_existence("racecar");
61 reverse_existence("abcd");
62 reverse_existence("banana");
63 reverse_existence("hello");
64 
65 sub reverse_existence($str) {
66     say "Input: \"$str\"";
67     my $rev = join("", reverse split //, $str);
68     foreach my $i (0..length($str)-2) {
69         my $s = substr($str, $i, 2);
70         return say "Output: true" if $rev =~ m/$s/;
71     }
72     say "Output: false";
73 }