RogerBW's Blog

The Weekly Challenge 205: Third Exclusive 26 February 2023

I’ve been doing the Weekly Challenges. The latest involved list parsing and combinations. (Note that this closes today.)

Task 1: Third Highest

You are given an array of integers.

Write a script to find out the Third Highest if found otherwise return the maximum.

My approach here is to get the distinct values in the input list, reverse sort it, and then pull either the third entry (if it exists) or the first. (The problem doesn't specify what's to be done with an empty list; I choose to return zero.)

Perl:

sub thirdhighest($l) {
  my @v = reverse sort keys %{{map {$_ => 1} @{$l}}};
  if (scalar @v == 0) {
    return 0;
  } elsif (scalar @v <= 2) {
    return $v[0];
  } else {
    return $v[2];
  }
}

I think the most elegant code here is in Rust (for which I was going to use a HashSet, but it turns out that dedup() is a thing for vectors).

fn thirdhighest(l: Vec<i32>) -> i32 {
    let mut v = l.clone();
    v.sort();
    v.dedup();
    v.reverse();
    match v.len() {
        0 => 0,
        1..=2 => v[0],
        _ => v[2],
    }
}

Task 2: Maximum XOR

You are given an array of integers.

Write a script to find the highest value obtained by XORing any two distinct members of the array.

So it's time to dust off the combinations generator, last seen in 203 task 1. Some languages have this readily available; others don't.

Python:

from itertools import combinations

def maximumxor(l):
  m = []
  for c in combinations(l, 2):
    m.append(c[0] ^ c[1])
  return max(m)

I finally got round to implementing Knuth's lexicographic combination algorithm [TAoCP volume 4 § 7.2.1.3] in PostScript, complete with its slightly odd ordering, and that's now in the library for future use. (The library itself has moved to Codeberg as part of my general disentanglement from github at least for my own projects.)

PostScript:

/combinations {
    4 dict begin
    /k exch def
    /arr exch def
    /c [
        0 1 k 1 sub { } for
        arr length
        0
    ] def
    [
        {
            [
                k 1 sub -1 0 {
                    c exch get arr exch get
                } for
            ]
            /j 0 def
            {
                c j get 1 add c j 1 add get ne {
                    exit
                } if
                c j j put
                /j j 1 add def
            } loop
            j k ge {
                exit
            } if
            c j c j get 1 add put
        } loop
    ]
    end
} bind def

/maximumxor {
    [ exch
      2 combinations {
          dup 0 get exch 1 get xor
      } forall
    ] listmax
} bind def

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