RogerBW's Blog

The Weekly Challenge 372: Space is the Largest Place 10 May 2026

I’ve been doing the Weekly Challenges. The latest involved various sorts of string mangling. (Note that this ends today.)

Task 1: Rearrange Spaces

You are given a string text of words that are placed among 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.

This seems quite fiddly, but it falls into steps.

  • Split the words into a list, and count the spaces.

  • Work out the number of spaces per division, and the remainder.

  • Join the words by the number of spaces per division, and then add the remainder onto the end.

Thus in Ruby:

def rearrangespaces(a)
  words = []
  spaces = 0
  ww = ""

Rather than use the built-in split, which would lose some information I need, I'll look through the input one character at a time.

  a.chars.each do |c|

If it's a space, increment the space count.

    if c == ' '
      spaces += 1

And if there was a word in progress, add it to the list and clear the word in progress.

      if ww != ""
        words.push(ww)
        ww = ""
      end

Otherwise, add a character to the word in progress.

    else
      ww += c
    end
  end

If we ended with a word in progress, push that on too.

  if ww != ""
    words.push(ww)
  end

If there aren't any divisions, all the spaces will go in the remainder.

  spdiv = 0
  remainder = spaces

Count the number of divisions to see if we can do better.

  divs = words.size - 1

If we have any, allocate the spaces as evenly as we can, and put the rest in the remainder.

  if divs > 0
    spdiv, remainder = spaces.divmod(divs)
  end

Build the joined list of words.

  out = words.join(" " * spdiv)

Add the remainder if any.

  if remainder > 0
    out += " " * remainder
  end
  out
end

Task 2: Largest Substring

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.

It doesn't actually matter what's in the substring, only how long it is.

So what I actually want is the maximum distance between a pair of identical characters.

Obviously I'll have to search all possible pairs of start and end points, which is going to be O(N²). But if I search the most-separated pairs first, I can potentially cut things short and just return with the first match I find, because that will have the maximum distance that's present.

Thus in Perl:

sub largestsubstring($a) {

Get a list of characters, for convenient indexing.

  my @cc = split '',$a;

Start with the longest possible inter-character gap and decrement until we get a match.

  foreach my $offset (reverse(1 .. $#cc)) {

Try each starting point that will have another character offset characters later.

    foreach my $x (0 .. $#cc - $offset) {

If there's a match, return that length immediately.

      if ($cc[$x] eq $cc[$x + $offset]) {
        return $offset - 1;
      }
    }
  }

If we get to the end with no match (which none of the examples does), return -1.

  -1;
}

Full code on codeberg.

Add A Comment

Your Name
Your Email
Your Comment

Note that I will only approve comments that relate to the blog post itself, not ones that relate only to previous comments. This is to ensure that the blog remains outside the scope of the UK's Online Safety Act (2023).

Your submission will be ignored if any field is left blank, but your email address will not be displayed. Comments will be processed through markdown.

Search
Archive
Tags 1920s 1930s 1940s 1950s 1960s 1970s 1980s 1990s 2000s 2010s 2300ad 3d printing action advent of code aeronautics aikakirja anecdote animation anime army astronomy audio audio tech aviation base commerce battletech bayern beer boardgaming book of the week bookmonth chain of command children chris chronicle church of no redeeming virtues cold war comedy computing contemporary cornish smuggler cosmic encounter coup covid-19 crime crystal cthulhu eternal cycling dead of winter disaster doctor who documentary drama driving drone ecchi economics en garde espionage essen 2015 essen 2016 essen 2017 essen 2018 essen 2019 essen 2022 essen 2023 essen 2024 essen 2025 existential risk falklands war fandom fanfic fantasy feminism filk film firefly first world war flash point flight simulation food garmin drive gazebo genesys geocaching geodata gin gkp gurps gurps 101 gus harpoon historical history horror horrorm science fiction hugo 2014 hugo 2015 hugo 2016 hugo 2017 hugo 2018 hugo 2019 hugo 2020 hugo 2021 hugo 2022 hugo 2023 hugo 2024 hugo 2025 hugo-nebula reread humour in brief avoid instrumented life javascript julian simpson julie enfield kickstarter kotlin learn to play leaving earth linux liquor lovecraftiana lua mecha men with beards mpd museum music mystery naval noir non-fiction one for the brow openscad opera parody paul temple perl perl weekly challenge photography podcast poetry politics postscript powers prediction privacy project woolsack pyracantha python quantum rail raku ranting raspberry pi reading reading boardgames social real life restaurant review reviews romance rpg a day rpgs ruby rust scala science fiction scythe second world war security shipwreck simutrans smartphone south atlantic war squaddies stationery steampunk stuarts suburbia superheroes suspense talon television the resistance the weekly challenge thirsty meeples thriller tin soldier torg toys trailers travel type 26 type 31 type 45 typst vietnam war war wargaming weather wives and sweethearts writing about writing x-wing young adult
Special All book reviews, All film reviews
Produced by aikakirja v0.1