The weekly challenge 380 - Task 1: Sum of Frequencies
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-380/#TASK1 3 # 4 # Task 1: Sum of Frequencies 5 # ========================== 6 # 7 # You are given a string consisting of English letters. 8 # 9 # Write a script to find the vowel and consonant with maximum frequency. Return 10 # the sum of two frequencies. 11 # 12 ## Example 1 13 ## 14 ## Input: $str = "banana" 15 ## Output: 5 16 ## 17 ## Vowel: "a" appears 3 times. 18 ## Consonant: "n" appears 2 times, "b" appears 1 time. 19 ## 20 ## Max frequency of vowel: 3 21 ## Max frequency of consonant: 2 22 # 23 ## Example 2 24 ## 25 ## Input: $str = "teestett" 26 ## Output: 7 27 ## 28 ## Vowel: "e" appears 3 times. 29 ## Consonant: "t" appears 4 times, "s" appears 1 time. 30 ## 31 ## Max frequency of vowel: 3 32 ## Max frequency of consonant: 4 33 # 34 ## Example 3 35 ## 36 ## Input: $str = "aeiouuaa" 37 ## Output: 3 38 ## 39 ## Vowel: "a" appears 3 times, "u" 2 times, "e", "i", "o" 1 time each. 40 ## Consonant: None. 41 ## 42 ## Max frequency of vowel: 3 43 ## Max frequency of consonant: 0 44 # 45 ## Example 4 46 ## 47 ## Input: $str = "rhythm" 48 ## Output: 2 49 ## 50 ## Vowel: None 51 ## Consonant: "h" appears 2 times, "r", "y", "t", "m" 1 time each. 52 ## 53 ## Max frequency of vowel: 0 54 ## Max frequency of consonant: 2 55 # 56 ## Example 5 57 ## 58 ## Input: $str = "x" 59 ## Output: 1 60 ## 61 ## Vowel: None 62 ## Consonant: "x" appears 1 time. 63 ## 64 ## Max frequency of vowel: 0 65 ## Max frequency of consonant: 1 66 # 67 ############################################################ 68 ## 69 ## discussion 70 ## 71 ############################################################ 72 # 73 # We count all vowels / consonants properly, storing the count 74 # in a hash for each. Then we just need to add the maximum 75 # of the values in both hashes. 76 77 use v5.36; 78 use List::Util qw(max); 79 80 sum_of_frequencies( "banana" ); 81 sum_of_frequencies( "teestett" ); 82 sum_of_frequencies( "aeiouuaa" ); 83 sum_of_frequencies( "rhythm" ); 84 sum_of_frequencies( "x" ); 85 86 sub sum_of_frequencies($str) { 87 say "Input: \"$str\""; 88 my $vowels = { "a" => 0 }; 89 my $consonants = { "b" => 0 }; 90 foreach my $char (split //, $str) { 91 if($char =~ m/[aeiou]/) { 92 $vowels->{$char}++; 93 } else { 94 $consonants->{$char}++; 95 } 96 } 97 say "Output: " . (max(values(%$vowels)) + max(values(%$consonants))); 98 }