perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 392 - Task 1: Convert Palindrome

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-392/#TASK1
 3 #
 4 # Task 1: Convert Palindrome
 5 # ==========================
 6 #
 7 # You are given a string.
 8 #
 9 # Write a script to convert the given string to palindrome by adding characters
10 # in front of it.
11 #
12 ## Example 1
13 ##
14 ## Input: $str = "pinnipeds"
15 ## Output: "sdepinnipeds"
16 #
17 ## Example 2
18 ##
19 ## Input: $str = "abcd"
20 ## Output: "dcbabcd"
21 #
22 ## Example 3
23 ##
24 ## Input: $str = "bananas"
25 ## Output: "sananabananas"
26 #
27 ## Example 4
28 ##
29 ## Input: $str = "dissident"
30 ## Output: "tnedissident"
31 #
32 ## Example 5
33 ##
34 ## Input: $str = "cailliachs"
35 ## Output: "shcailliachs"
36 #
37 ############################################################
38 ##
39 ## discussion
40 ##
41 ############################################################
42 #
43 # First, we find the longest palindrom already existing at the
44 # beginning of $str, then we prepend the reverse of the remainder
45 # to the whole string.
46 
47 use v5.36;
48 
49 
50 convert_palindrome("pinnipeds");
51 convert_palindrome("abcd");
52 convert_palindrome("bananas");
53 convert_palindrome("dissident");
54 convert_palindrome("cailliachs");
55 
56 sub convert_palindrome($str) {
57     say "Input: \"$str\"";
58     my @chars = split //, $str;
59     foreach my $i (0..$#chars) {
60         my $end = $#chars - $i;
61         if(is_palindrome(@chars[0..$end])) {
62             return say "Output: \"" . join("", reverse @chars[$end+1..$#chars]) . "$str\"";
63         }
64     }
65 }
66 
67 sub is_palindrome(@chars) {
68     my $str1 = join("", @chars);
69     my $str2 = join("", reverse @chars);
70     return $str1 eq $str2;
71 }