Robbie Hatley’s Solutions, in Perl, for The Weekly Challenge #372 (“Rearrange Spaces” and “Largest Substring”)

For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle with two parts, with a new pair of tasks each Monday. You can find it here: The Weekly Challenge

The Weekly Challenge for the week of 2026-05-04 through 2026-05-10 is #372. The tasks for challenge #372 are as follows:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 372-1: Rearrange Spaces
Submitted by: Mohammad Sajid Anwar
You are given a string text of words that are placed among a
number of spaces. Write a script to rearrange the spaces so that
there is an equal number of spaces between every pair of adjacent
words and that number is maximised. If you can’t distribute,
place the extra spaces at the end. Finally return the string.

I use this procedure:

  1. Count available spaces s.
  2. Trim leading and trailing spaces.
  3. Split string to @words on spaces.
  4. Count gaps between words (n words means n-1 gaps).
  5. Form quotient q and remainder r of spaces/gaps. (But if 0 == gaps, q=0 and r=s.)
  6. return join(@words, ' ' x $q) . (' ' x $r);

Robbie Hatley's Perl Solution to The Weekly Challenge 372-1

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 372-2: Largest Substring
Submitted by: Mohammad Sajid Anwar
You are given a string. Write a script to return the length of
the largest substring between two equal characters excluding the
two characters. Return -1 if there is no such substring.

I make a pair of nested three-part loops, note all pairs of equal characters, and track longest length of substrings between such pairs.

Robbie Hatley's Perl Solution to The Weekly Challenge 372-2

That's it for challenge 372; see you on challenge 373!

Comments

Popular posts from this blog

Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #334 (“Range Sum” and “Nearest Valid Point”)

Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #336 (“Equal Group” and “Final Score”)

Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #326 (“Day of Year” and “Decompressed List”)