The weekly challenge 279 - Task 2: Split String

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-279/#TASK2
 3 #
 4 # Task 2: Split String
 5 # ====================
 6 #
 7 # You are given a string, $str.
 8 #
 9 # Write a script to split the given string into two containing exactly same
10 # number of vowels and return true if you can otherwise false.
11 #
12 ## Example 1
13 ##
14 ## Input: $str = "perl"
15 ## Ouput: false
16 #
17 ## Example 2
18 ##
19 ## Input: $str = "book"
20 ## Ouput: true
21 ##
22 ## Two possible strings "bo" and "ok" containing exactly one vowel each.
23 #
24 ## Example 3
25 ##
26 ## Input: $str = "good morning"
27 ## Ouput: true
28 ##
29 ## Two possible strings "good " and "morning" containing two vowels each or
30 ## "good m" and "orning" containing two vowels each.
31 #
32 ############################################################
33 ##
34 ## discussion
35 ##
36 ############################################################
37 #
38 # We turn $str into an array of characters, then we check at each position
39 # whether a split right there would create two substrings with the same
40 # amount of vowels.
41 # A helper function takes care of counting the vowels in an array of characters.
42 
43 use strict;
44 use warnings;
45 
46 split_string("perl");
47 split_string("book");
48 split_string("good morning");
49 
50 sub split_string {
51    my $str = shift;
52    print "Input: \"$str\"\n";
53    my @letters = split //, $str;
54    foreach my $i (0..$#letters) {
55       return print "Output: true\n" if count_vowels(@letters[0..$i]) == count_vowels(@letters[$i+1..$#letters]);
56    }
57    return print "Output: false\n";
58 }
59 
60 sub count_vowels {
61    my @chars = @_;
62    my $count = 0;
63    my $vowels = { a => 1, e => 1, i => 1, o => 1, u => 1,
64       A => 1, E => 1, I => 1, O => 1, U => 1, };
65    foreach my $char (@chars) {
66       $count++ if $vowels->{$char};
67    }
68    return $count;
69 }