perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 348 - Task 1: String Alike

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-348/#TASK1
 3 #
 4 # Task 1: String Alike
 5 # ====================
 6 #
 7 # You are given a string of even length.
 8 #
 9 # Write a script to find out whether the given string can be split into two
10 # halves of equal lengths, each with the same non-zero number of vowels.
11 #
12 ## Example 1
13 ##
14 ## Input: $str = "textbook"
15 ## Output: false
16 ##
17 ## 1st half: "text" (1 vowel)
18 ## 2nd half: "book" (2 vowels)
19 #
20 #
21 ## Example 2
22 ##
23 ## Input: $str = "book"
24 ## Output: true
25 ##
26 ## 1st half: "bo" (1 vowel)
27 ## 2nd half: "ok" (1 vowel)
28 #
29 #
30 ## Example 3
31 ##
32 ## Input: $str = "AbCdEfGh"
33 ## Output: true
34 ##
35 ## 1st half: "AbCd" (1 vowel)
36 ## 2nd half: "EfGh" (1 vowel)
37 #
38 #
39 ## Example 4
40 ##
41 ## Input: $str = "rhythmmyth"
42 ## Output: false
43 ##
44 ## 1st half: "rhyth" (0 vowel)
45 ## 2nd half: "mmyth" (0 vowel)
46 #
47 #
48 ## Example 5
49 ##
50 ## Input: $str = "UmpireeAudio"
51 ## Output: false
52 ##
53 ## 1st half: "Umpire" (3 vowels)
54 ## 2nd half: "eAudio" (5 vowels)
55 #
56 ############################################################
57 ##
58 ## discussion
59 ##
60 ############################################################
61 #
62 # We turn the string into an array of characters. Then we walk from
63 # both the left and the right side at the same time, counting the
64 # vowels as we go along. In the end we check if both halves of the
65 # string had the same amount of vowels, and if so whether that number
66 # is bigger than 1.
67 
68 use v5.36;
69 
70 string_alike("textbook");
71 string_alike("book");
72 string_alike("AbCdEfGh");
73 string_alike("rhythmmyth");
74 string_alike("UmpireeAudio");
75 
76 sub string_alike($str) {
77     say "Input: \"$str\"";
78     my @chars = split //, $str;
79     my $vl = 0;
80     my $vr = 0;
81     while(@chars) {
82         my $l = shift @chars;
83         my $r = pop @chars;
84         $vl++ if is_vowel($l);
85         $vr++ if is_vowel($r);
86     }
87     if($vl == $vr) {
88         if($vl > 0) {
89             return say "Output: true";
90         }
91     }
92     say "Output: false";
93 }
94 
95 sub is_vowel($c) {
96     $c = lc($c);
97     return 1 if $c eq "a" or $c eq "e" or $c eq "i" or $c eq "o" or $c eq "u";
98     return 0;
99 }