RogerBW's Blog

The Weekly Challenge 239: Same and Consistent 22 October 2023

I’ve been doing the Weekly Challenges. The latest involved joining strings and matching characters. (Note that this ends today.)

Task 1: Same String

You are given two arrays of strings.

Write a script to find out if the word created by concatenating the array elements is the same.

Pretty straightforward in almost any language, even PostScript with my extensions.

/samestring {
    () strjoin exch
    () strjoin
    deepeq
} bind def

More conventionally in Ruby:

def samestring(a, b)
  return a.join("") == b.join("")
end

Task 2: Consistent Strings

You are given an array of strings and allowed string having distinct characters.

A string is consistent if all characters in the string appear in the string allowed.

Write a script to return the number of consistent strings in the given array.

The obvious algorithm is to test one character at a time, and bail out if any of them isn't in the verification input. But most of the languages I use have some kind of short-cut for this: Rust, Ruby, Raku and Perl (via List::Utils) each have an all method on an interable plus a test function which returns a boolean, and I'd already written one for PostScript. Scala calls its all and any forall and exists, and JavaScript calls them every and some, but they work basically the same way. (Except Raku's. And Lua doesn't really like the idea of iterables at all.)

This use of an all function is not necessarily any more efficient than writing out, as I often have for these things, something along the lines of:

for n in items {
  if !test(n) {
    return false
  }
}
return true

but it does mean that this kind of general-purpose workhorse code is moved away into a different place from the important and task-specific part, leaving the latter easier to comprehend.

So all the languages except Lua and Raku get something like this Rust:

fn consistentstrings(a: Vec<&str>, v: &str) -> u32 {
    let vs = v.chars().collect::<HashSet<char>>();
    a.iter().filter(|s| s.chars().unique().all(|c| vs.contains(&c))).count()
        as u32
}

"For each string in a, count it if each unique character in that string exists in vs; return the total count."

Raku's all uses a junction structure which needs a somewhat different approach. Where in most languages I'm doing something like

characters.all(|char| test(char))

Raku prefers

test(characters.all)

or in full

sub consistentstrings(@a, $v) {
    my $vs = $v.comb.Set;
    return @a.grep({$vs{$_.comb.Set.keys.all}:exists}).elems;
}

It's interestingly expressive, though I think it's pretty much unique to this language.

Full code on github.

Comments on this post are now closed. If you have particular grounds for adding a late comment, comment on a more recent post quoting the URL of this one.

Search
Archive
Tags 1920s 1930s 1940s 1950s 1960s 1970s 1980s 1990s 2000s 2010s 3d printing action advent of code aeronautics aikakirja anecdote animation anime army astronomy audio audio tech base commerce battletech 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 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 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 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 opera parody paul temple perl perl weekly challenge photography podcast politics postscript powers prediction privacy project woolsack pyracantha python quantum rail raku ranting raspberry pi reading reading boardgames social real life restaurant 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 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