RogerBW's Blog

The Weekly Challenge 217: Sorted Max 21 May 2023

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

Task 1: Sorted Matrix

You are given a n x n matrix where n >= 2.

Write a script to find 3rd smallest element in the sorted matrix.

Examples indicate that no deduplication is needed, so there will always be a third-smallest element.

Clearly the approach is to flatten everything into a list, sort it, and extract the third element. Flattening is one of those relatively new features that languages do in very different ways (or, in some cases, not at all – I confess I've never particularly missed it in Perl). In Raku:

sub sortedmatrix(@matrix) {
    my @n = @matrix[*;*];
    return @n.sort({$^a <=> $^b})[2];
}

JavaScript:

    var n = matrix.flat();

Python:

  n = list(chain.from_iterable(matrix))

I'm father fond of the variable-free* PostScript:

/sortedmatrix {
    [ exch
      {
          aload pop
      } forall
    ] quicksort 2 get
} bind def

* well, almost, my quicksort uses a lot of variables…

Task 2: Max Number

You are given a list of positive integers.

Write a script to concatenate the integers to form the highest possible value.

The naïve approach would be to try all possible orderings. Obviously that would get expensive very quickly.

In most situations one can simply stringify each number, reverse-sort in string order, and concatenate the results (because the highest numbers should always be in the leftmost positions in the output). This looks pretty easy, but there's a fiddly edge case (which is why example 5 exists): when two strings aren't of equal length, problems arise.

56 should appear before 5 (565 > 556).

55 can appear before or after 5.

54 should appear after 5 (554 > 545).

My solution is to extend each string by its final character until all strings are the same length - so the 5 above becomes 55 for string-ordering purposes.

Then I have the problem of wanting to sort the modified strings and use that order to reorder the original strings. I use something like a Schwartzian transform, except that in most languages I sort a list of indices rather than a composite variable.

Kotlin:

fun maxnumber(lst: List<Int>): Int {

po is the input list, stringified.

    val po = lst.map {it.toString()}

pl is the maximum length of any of those strings.

    val pl = po.map {it.length}.maxOrNull()!!

pm will hold the extended strings.

    var pm = ArrayList<String>()
    for (so in po) {
        var sm = so

If this one is shorter than the longest, extend it by its last character.

        if (so.length < pl) {
            val c = so.lastOrNull()!!
            for (_i in 1 .. pl - so.length) {
                sm += c
            }
        }
        pm.add(sm)
    }

Generate the list of indices.

    var pi = ArrayList((0 .. pm.size - 1).toList())

Sort it based on the contents of pm.

    pi.sortByDescending {pm[it]}

Use it to read out po in the right order.

    var out = ""
    for (st in pi) {
        out += po[st]
    }

And convert back to integer.

    return out.toInt()
}

In PostScript I ended up extending my sorting library to support multiple ways of indicating a custom sort order: you can now specify a comparator function, or a list of keys, or a function to generate keys.

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