The weekly challenge 353 - Task 1: Max Words
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-353/#TASK1 3 # 4 # Task 1: Max Words 5 # ================= 6 # 7 # You are given an array of sentences. 8 # 9 # Write a script to return the maximum number of words that appear in a single 10 # sentence. 11 # 12 ## Example 1 13 ## 14 ## Input: @sentences = ("Hello world", "This is a test", "Perl is great") 15 ## Output: 4 16 # 17 # 18 ## Example 2 19 ## 20 ## Input: @sentences = ("Single") 21 ## Output: 1 22 # 23 # 24 ## Example 3 25 ## 26 ## Input: @sentences = ("Short", "This sentence has seven words in total", "A B C", 27 ## "Just four words here") 28 ## Output: 7 29 # 30 # 31 ## Example 4 32 ## 33 ## Input: @sentences = ("One", "Two parts", "Three part phrase", "") 34 ## Output: 3 35 # 36 # 37 ## Example 5 38 ## 39 ## Input: @sentences = ("The quick brown fox jumps over the lazy dog", "A", 40 ## "She sells seashells by the seashore", 41 ## "To be or not to be that is the question") 42 ## Output: 10 43 # 44 ############################################################ 45 ## 46 ## discussion 47 ## 48 ############################################################ 49 # 50 # We split each sentence into individual words and count those, 51 # keeping track of the maximum. Pretty straight forward. 52 # 53 use v5.36; 54 55 max_words("Hello world", "This is a test", "Perl is great"); 56 max_words("Single"); 57 max_words("Short", "This sentence has seven words in total", "A B C", 58 "Just four words here"); 59 max_words("One", "Two parts", "Three part phrase", ""); 60 max_words("The quick brown fox jumps over the lazy dog", "A", 61 "She sells seashells by the seashore", 62 "To be or not to be that is the question"); 63 64 sub max_words(@sentences) { 65 say "Input: (\"" . join("\",\n\t\"", @sentences) . "\")"; 66 my $max = 0; 67 foreach my $sentence (@sentences) { 68 my @words = split /\W/, $sentence; 69 $max = scalar(@words) if scalar(@words) > $max; 70 } 71 say "Output: $max"; 72 }