perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 374 - Task 1: Count Vowel

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-374/#TASK1
 3 #
 4 # Task 1: Count Vowel
 5 # ===================
 6 #
 7 # You are given a string.
 8 #
 9 # Write a script to return all possible vowel substrings in the given string. A
10 # vowel substring is a substring that only consists of vowels and has all five
11 # vowels present in it.
12 #
13 ## Example 1
14 ##
15 ## Input: $str = "aeiou"
16 ## Output: ("aeiou")
17 #
18 ## Example 2
19 ##
20 ## Input: $str = "aaeeeiioouu"
21 ## Output: ("aaeeeiioou", "aaeeeiioouu", "aeeeiioou", "aeeeiioouu")
22 ##
23 ## NOTE: Updated output [2025-05-18]
24 #
25 ## Example 3
26 ##
27 ## Input: $str = "aeiouuaxaeiou"
28 ## Output: ("aeiou", "aeiou", "eiouua", "aeiouu", "aeiouua")
29 ##
30 ## NOTE: Updated output [2025-05-18]
31 #
32 ## Example 4
33 ##
34 ## Input: $str = "uaeiou"
35 ## Output: ("aeiou", "uaeio", "uaeiou")
36 #
37 ## Example 5
38 ##
39 ## Input: $str = "aeioaeioa"
40 ## Output: ()
41 #
42 ############################################################
43 ##
44 ## discussion
45 ##
46 ############################################################
47 #
48 # We create all possible substrings, then we check whether there
49 # are any non-vowels in them and if they contain all vowels. In
50 # that case, we keep them.
51 
52 use v5.36;
53 
54 count_vowel("aeiou");
55 count_vowel("aaeeeiioouu");
56 count_vowel("aeiouuaxaeiou");
57 count_vowel("uaeiou");
58 count_vowel("aeioaeioa");
59 
60 sub count_vowel($str) {
61     say "Input: \"$str\"";
62     my @result = ();
63     foreach my $i (0..length($str)-1) {
64         foreach my $j (1..length($str)-$i) {
65             my $s = substr($str, $i, $j);
66             push @result, $s if has_all_vowels($s);
67         }
68     }
69     say "Output: (" . join(", ", map { "\"$_\"" } @result) . ")";
70 }
71 
72 sub has_all_vowels($str) {
73     my %chars = ();
74     map { $chars{"$_"} = 1 } split //, $str;
75     return 0 if $str =~ m/[^aeiou]/;
76     return 0 unless $chars{"a"};
77     return 0 unless $chars{"e"};
78     return 0 unless $chars{"i"};
79     return 0 unless $chars{"o"};
80     return 0 unless $chars{"u"};
81     return 1;
82 }