Perl Weekly Challenge #225 - Words to the Max and Diff Sum

Hi all! Back this week with both solutions to The Weekly Challenge for once. We've got a word counting challenge and one that I really don't know how to explain. You have to see the challenge to understand it.

Max Words

So this challenge is just to tell us what the longest sentence in a set of sentences is. How many words does it have? A very simple easy solution can follow:

my $highest;
foreach (@ARGV) {
    my @words = split(/ /, $_);
    shift @words if !$words[0];
    $highest = scalar @words if scalar @words > $highest;
say $highest;

We take the input sentences (in quotes) and split them by spaces. Now, I tested and splitting by space puts an empty element at the start of the array, so if there is such an empty element we remove it with the shift. Then we check the number of words in this sentence and replace the existing champion if this one is the highest. That one's pretty simple and took just about 15 minutes to write and test.

Left Right Sum Diff

No idea what the actual practical purpose of this one is, but it's an interesting challenge and a lot simpler than I initally thought, although I realized in the middle there were some additional cases to handle from what I was thinking.

The goal is to split a list of integers into @left, made of (0, $ints[0], $ints[0] + $ints[1], etc.) and @right, made of 'etc., $ints[-2] + $ints[-1], $ints[-1], 0). Then we iterate through and for each pair we take the absolute difference between$left[$]and$right[$]`.

So here's the code:

my @ints = @ARGV;
my (@left, @right, @diff);
push @left, 0;
unshift @right, 0;
if ($#ints) {
    foreach (1..$#ints) {
        push @left, $left[$_ - 1] + $ints[$_ - 1];
        unshift @right, $right[-$_] + $ints[-$_];
foreach (0..$#ints) {
    $diff[$_] = abs($left[$_] - $right[$_]);
say $_ for @diff;

First we put the zeros on each list. That's just in case we have a integer list like the second example, with just one number in the list. Then if we have additional integers we count and add numbers to the right side of the @left list and the left side of the @right list.

We loop through both completed lists and we compute the absolute difference, then print the list one-by-one. Voila! Again, not sure what the practical application is, but an interesting challenge. Many thanks to Mohammad and an enjoyable pair of challenges. I also appreciate being the June champion, so you'll hear more of my bio when it's released.

Have a great week! See you next week.

Leave a comment

About oldtechaa

user-pic Just getting back into Perl programming. I have a personal project, SeekMIDI, a small graphical MIDI sequencer.