Words and shopping
Weekly challenge 353 — 22 December 2025
Week 353: 22 Dec 2025
You are given an array of sentences. Write a script to return the maximum number of words that appear in a single sentence.
Example 1 Input: @sentences = ('Hello world', 'This is a test', 'Perl is great') Output: 4 Example 2 Input: @sentences = ('Single') Output: 1 Example 3 Input: @sentences = ('Short', 'This sentence has seven words in total', 'A B C', 'Just four words here') Output: 7 Example 4 Input: @sentences = ('One', 'Two parts', 'Three part phrase', '') Output: 3 Example 5 Input: @sentences = ('The quick brown fox jumps over the lazy dog', 'A', 'She sells seashells by the seashore', 'To be or not to be that is the question') Output: 10
Clearly the solution to this is to count th words in each sentence and find the largest.
The only slight doubt is where words include
non-letters, such as George's 4 egg-cups,
but failing any instruction to the contrary I assumed
that words are groups of characters separated by
one or more whitespace characters (\s in regex speak).
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2025-12-22 use utf8; # Week 353 - task 1 - Max words use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; max_words('Hello world', 'This is a test', 'Perl is great'); max_words('The quick brown fox jumps over the lazy dog', 'A', 'She sells seashells by the seashore', 'To be or not to be that is the question'); max_words('one', 'two', 'three'); max_words("George's boots are clean"); max_words("she said 'ice-cream is lovely'"); max_words(); sub max_words { my (@sentences, $max_words, $sentence, @words); # initialise @sentences = @_; $max_words = 0; # loop over sentences for $sentence (@sentences) { # split into words and count them @words = split('\s+', $sentence); $max_words = @words if @words > $max_words; } say qq{\nInput: [} . join('], [', @sentences) . ']'; say qq[Output: $max_words]; }
Input: [Hello world], [This is a test], [Perl is great] Output: 4 Input: [The quick brown fox jumps over the lazy dog], [A], [She sells seashells by the seashore], [To be or not to be that is the question] Output: 10 Input: [one], [two], [three] Output: 1 Input: [George's boots are clean] Output: 4 Input: [she said 'ice-cream is lovely'] Output: 5 Input: [] Output: 0
Any content of this website which has been created by Peter Campbell Smith is in the public domain