RogerBW's Blog

The Weekly Challenge 229: Three, Two, Out of Order 13 August 2023

I’ve been doing the Weekly Challenges. The latest involved analysing strings and picking over lists. (Note that this ends today.)

Task 1: Lexicographic Order

You are given an array of strings. Write a script to delete element which is not lexicographically sorted (forwards or backwards) and return the count of deletions.

As usual I code to the test case, so I don't bother with the actual deletion. If that were required, the logic wouldn't change much anyway.


sub lexicographic(@a) {
    my $t = 0;

For each string…

    for @a -> $st {

Take the characters and sort them.

        my @q = $st.comb.sort;

If that's the same as the string, we have a forward sort, so continue.

        if (join('', @q) eq $st) {

Otherwise, reverse and test again.

        @q = reverse @q;
        if (join('', @q) eq $st) {

If we've got down to here, the string is not in order, so increment the count.

    return $t;

The other languages look every similar, even PostScript (using the 1 { ... } repeat trick to make a fake loop I can break out of with exit).

/lexicographic {
    2 dict begin
    0 exch
        /st exch def
        st s2a quicksort /q exch def
        1 {
            q a2s st deepeq {
            } if
            q reverse a2s st deepeq {
            } if
            1 add
        } repeat
    } forall
} bind def

Task 2: Two out of Three

You are given three array of integers.

Write a script to return all the elements that are present in at least 2 out of 3 given arrays.

Hashes with defaults again, as seen in last week's part 1. Python:

from collections import defaultdict

def twoofthree(a):

Set up my default-zero hash.

  ct = defaultdict(lambda: 0)

For each of the input lists (I don't care that there are exactly three of them):

  for iv in a:

Convert it to a set (we don't care how many times it's in this list, just whether it's here or not)

    for n in set(iv):

and increment the count of lists in which that value has appeared.

      ct[n] += 1

Then filter that counter hash for items that occur at least twice.

  out = list(k for k, v in ct.items() if v >= 2)

We've given up ordering by using a hash, so sort the final output.

  return out

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.

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 aviation 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 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 2022 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