RogerBW's Blog

The Weekly Challenge 245: Largest Sort 03 December 2023

I’ve been doing the Weekly Challenges. The latest involved keyed sorting and digit searching. (Note that this ends today.)

Task 1: Sort Language

You are given two array of languages and its popularity.

Write a script to sort the language based on popularity.

This is basically a sort by external key, but we have a separate list of sort keys rather than a mapping function. Building a hashmap would be one way to do it, but that fails if any key values are non-unique; so instead I take a third list, of indices into the other two. Sort the indices by the popularity value of each, then output a map of the language name for each index. Some similarity to last week's 244.1, in that the last line tends to be a map and return.

My PostScript library already has a ".with_keylist" mode for its sort routines, which does all the work this behind the scenes.

/sortlanguage {
    quicksort.with_keylist
} bind def

But more conventionally in JavaScript:

function sortlanguage(langs, popularities) {
    let ix = Array(langs.length).fill().map((element, index) => index);
    ix.sort(function(a,b) {
        return popularities[a] - popularities[b];
    });
    return ix.map(n => langs[n]);
}

Task 2: Largest of Three

You are given an array of integers >= 0.

Write a script to return the largest number formed by concatenating some of the given integers in any order which is also multiple of 3.

There's an efficiency gain to be had in the specific constraints of the problem, since the divisibility test is by 3: any set of base-10 digits will preserve its divisibility 3 regardless of its order. And the maximum value of that set will be the one with the highest digits first. So those are the only permutations we need to look at. As with 244 task 2 last week, I pre-sort the digit array (in this case I want it descending), then test each combination at each length.

A modularity test is probably slower than a comparison, so I do the comparison first; languages which short-circuit get the chance to do so.

I thought about bailing out after the length at which the first candidate max value is found, but what about (2, 3)? No two-digit combination is divisible by 3, but at least one one-digit combination is.

Raku:

sub largestofthree(@digits) {
    my @ordered = @digits.sort({$^b <=> $^a});
    my $mx = 0;
    for (0 .. @ordered.end).reverse -> $n {
        for combinations(@ordered, $n + 1) -> @c {
            my $t = 0;
            for @c -> $d {
                $t *= 10;
                $t += $d;
            }
            if ($t > $mx && $t % 3 == 0) {
                $mx = $t;
            }
        }
    }
    return $mx;
}

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