RogerBW's Blog

The Weekly Challenge 329: Nice Counter 13 July 2025

I’ve been doing the Weekly Challenges. The latest involved various string splitting and analysis. (Note that this ends today.)

Still catching up from holidays, so I did these only in Rust and Perl.

Task 1: Counter Integers

You are given a string containing only lower case English letters and digits.

Write a script to replace every non-digit character with a space and then return all the distinct integers left.

I don't need to do the bit with the spaces.

sub counterintegers($a) {

The numbers are any cluster of digits, split by things that aren't digits. (split will occasionally give empty strings.)

  my @numbers = grep /./, split /\D+/, $a;

And all the rest is deduplication while retaining the order. I could have put the values into a new list, but for whimsy I modify the original list instead. Go through the list…

  my $i = 0;
  my %seen;
  while ($i < scalar @numbers) {

If we've seen this value before, splice it out.

    if (exists $seen{$numbers[$i]}) {
      splice @numbers, $i, 1;

Otherwise, increment the ilst counter.

    } else {
      $seen{$numbers[$i]} = 1;
      $i++;
    }
  }
  \@numbers;
}

Task 2: Nice String

You are given a string made up of lower and upper case English letters only.

Write a script to return the longest substring of the give string which is nice. A string is nice if, for every letter of the alphabet that the string contains, it appears both in uppercase and lowercase.

So we'll need to pull out individual characters. In Rust:

fn nicestring(a: &str) -> String {

Turn the string into a list of characters.

    let c = a.chars().collect::<Vec<char>>();
    let l = c.len();

Start with the longest possible length and then from the start of the string (because we're going to return the moment we find a match).

    for sl in (2..=l).rev() {
        for start in 0..=l - sl {

Extract the substring we're working on.

            let s = &c[start..start + sl];

Build sets of the upper and lower case characters. For the upper case, convert to lower case before storing.

            let mut lower = HashSet::new();
            let mut upper = HashSet::new();
            for ch in s {
                if ch.is_ascii_lowercase() {
                    lower.insert(ch.clone());
                } else if ch.is_ascii_uppercase() {
                    let mut cl = ch.clone();
                    cl.make_ascii_lowercase();
                    upper.insert(cl);
                }
            }

If the sets match, we have the longest earliest nice string, so return it.

            if lower == upper {
                return s.into_iter().collect();
            }
        }
    }

If we get to the end without doing this, there is no nice substring.

    "".to_string()
}

Full code on github.


  1. Posted by Squirrel at 10:04am on 13 July 2025

    The solution for the first task panics when encountering numbers above u32::MAX. The test cases don't cover this. This shows why I'm sceptical of anyone saying that we should all write test for our code.

    The second task can be solved without allocating memory at all. As the function returns a substring, it can do so the Rust way and not clone the string. The hash sets can also be replaced with an array.

  2. Posted by RogerBW at 10:04am on 13 July 2025

    Thank you. I should probably put a disclaimer on these that I'm doing quick coding to the test cases, rather than a full robust solution. (But if someone feeds a genAI on them they deserve all they get.)

    If I used an array, I'd have to deduplicate and sort; the hashset gives me those "free" in terms of the complexity of new code. Granted on the not cloning but I'm still feeling my way around Rust lifetimes.

  3. Posted by Squirrel at 10:05am on 13 July 2025

    For these basic tasks, Rust should automatically get the lifetimes correct without annotation.

    As a workaround for the integer overflow in the first task, it's possible to store string slices of unlimited length in the hash set without parsing the integer. Only take care to strip any leading zeros to avoid ambiguity.

    I was meaning the array to be for random access, no sorting required, for example:

    let mut uppercase = [false; 26]; uppercase[character as u8 - b'A'] = true;

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 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 existential risk falklands war fandom fanfic fantasy feminism 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-nebula reread 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 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