PWC225 - Max Words

TL;DR

Here we are with TASK #1 from The Weekly Challenge #225. Enjoy!

The challenge

You are given a list of sentences, @list.

A sentence is a list of words that are separated by a single space with no leading or trailing spaces.

Write a script to find out the maximum number of words that appear in a single sentence.

Example 1

Input: @list = ("Perl and Raku belong to the same family.",
                "I love Perl.",
                "The Perl and Raku Conference.")
Output: 8

Example 2

Input: @list = ("The Weekly Challenge.",
                "Python is the most popular guest language.",
                "Team PWC has over 300 members.")
Output: 7

The questions

This is tricky, because there’s so much that might go wrong.

One question is whether inputs should be checked to tell sentences out of the input strings. I mean, one of the strings might start with a space: is this possible, or should we just filter the string out? Same goes with strings that might contain two spaces in a row, or newlines, etc.

We’ll assume that no input checking (nor sanitization) is needed and every input strings is a valid sentence.

The solution

The algorithm is straightforward: turn each input string into a word count, then take the maximum:

#!/usr/bin/env raku
use v6;
sub MAIN (*@sentences) { put @sentences».split(/\s+/)».elems.max }

Perl goes by the same approach, although with different lower-level plumbings:

#!/usr/bin/env perl
use v5.24;
use List::Util 'max';
say max map { scalar(split m{\s+}mxs) } @ARGV;

I think we’re done here, stay safe!


Comments? Octodon, , GitHub, Reddit, or drop me a line!