RogerBW's Blog

The Weekly Challenge 213: Shortest Fun 23 April 2023

I’ve been doing the Weekly Challenges. The latest involved an unusual sort and a pathfinding problem. (Note that this is open until 23 April 2023.)

Task 1: Fun Sort

You are given a list of positive integers.

Write a script to sort the all even integers first then all odds in ascending order.

Normally for something like this I'd use a filter, grep or similar structure, but in this case I need to build two separate lists.

Raku shows off its rich core library:

sub funsort(@l0) {
    my %h = classify { $_ %% 2 ?? 'even' !! 'odd' }, @l0.sort();
    my @a;
    for ("even", "odd") -> $mode {
        if (%h{$mode}) {
            @a.append(%h{$mode}.List);
        }
    }
    return @a;
}

while in the other languages it was easier to be explicit, as in Python:

def funsort(l0):
  l = l0
  l.sort()
  a = []
  b = []
  for k in l:
    if k % 2 == 0:
      a.append(k)
    else:
      b.append(k)
  a.extend(b)
  return a

Task 2: Shortest Route

You are given a list of bidirectional routes defining a network of nodes, as well as source and destination node numbers.

Write a script to find the route from source to destination that passes through fewest nodes.

I've done Dijkstra before, but this time I did a simple exhaustive search without repetition. Using a breadth-first search guarantees that the first path found is a shortest path (because all length N paths are tested before any length N+1 paths), so we exit at that point.

Sets (which I think of as contentless hashes) are great. But Lua, Perl and PostScript don't have them, so I ended up using a hash and ignoring the value part.

Python, Rust and Ruby have set difference operators and I was able to use them. Raku does too, but I didn't manage to get that one to work.

In Rust and Python I carried a set of unused nodes along with the path-to-date, trading off memory to get a little more speed. In the other languages this was trickier, and I just worked it up on the fly. Here's the Rust.

fn shortestroute(r0: Vec<Vec<u32>>, origin: u32, destination: u32) -> Vec<u32> {

This goes in two stages. First, break down the input into a list of possible exits from each node. (Specifically, a map from each node to a set of exits.)

    let mut r: HashMap<u32, HashSet<u32>> = HashMap::new();
    for rt in r0 {
        for rp in rt.windows(2) {
            r.entry(rp[0])
                .and_modify(|s| {
                    (*s).insert(rp[1]);
                })
                .or_insert(HashSet::from([rp[1]]));
            r.entry(rp[1])
                .and_modify(|s| {
                    (*s).insert(rp[0]);
                })
                .or_insert(HashSet::from([rp[0]]));
        }
    }

Then, starting at the origin, build paths that go to to each exit, and do this repeatedly until we reach the destination. This is a fairly standard breadth-first search framework as I've used in many previous PWC entries.

    let mut out = Vec::new();
    let mut stack = VecDeque::new();
    stack.push_back((vec![origin], HashSet::from([origin])));
    while stack.len() > 0 {
        let s = stack.pop_front().unwrap();
        let l = s.0.last().unwrap();
        if *l == destination {
            out = s.0;
            break;
        } else {
            for pd in r.get(&l).unwrap().difference(&s.1) {
                let mut q = s.clone();
                q.0.push(*pd);
                q.1.remove(pd);
                stack.push_back(q);
            }
        }
    }
    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.

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