RogerBW's Blog

The Weekly Challenge 271: Sort the Maximum One 02 June 2024

I’ve been doing the Weekly Challenges. The latest involved matrix analysis, bit-counting and sorting. (Note that this ends today.)

Task 1: Maximum Ones

You are given a m x n binary matrix.

Write a script to return the row number containing maximum ones, in case of more than one rows then return smallest row number.

There are probably multiple ways to do this, but I took a fairly straightforward approach which ended up producing simple code. In PostScript:

/maximumones {
    0 dict begin

Since we know it's a binary matrix and we won't at any point care about column information, my first step is to convert the matrix to a list of row sums (= count of 1s).

    /ax exch { { add } reduce } map def

Then get the maximum value of any row.

    /am ax listmax def

Now iterate through them, returning the first index value that matches the maximum. (This can't in fact fail to return a value—at least one entry will intrinsically equal the maximum—but paranoia says I should have a default anyway.)

    -1
    ax enumerate.array {
        aload pop
        /n exch def
        /i exch def
        n am eq {
            pop i
            exit
        } if
    } forall
    1 add
    end
} bind def

Languages that have array searching built in can do that last part much less verbosely, for example Kotlin:

fun maximumones(a: List<List<Int>>): Int {
    val ax = a.map{it.sum()}.toList()
    val am = ax.maxOrNull()!!
    return ax.indexOf(am) + 1
}

Task 2: Sort by 1 bits

You are give an array of integers, @ints.

Write a script to sort the integers in ascending order by the number of 1 bits in their binary representation. In case more than one integers have the same number of 1 bits then sort them in ascending order.

Both parts of this problem have been in previous challenges: a count set bits function in 258 task 2, and a hierarchical sort with an expensive key function in 238 task 2. So for most of the languages I was able to combine my answers from the earlier code. In Perl for example:

sub popcount64($x0) {
  no warnings 'portable';
  use constant M1  => 0x5555555555555555;
  use constant M2  => 0x3333333333333333;
  use constant M4  => 0x0f0f0f0f0f0f0f0f;
  use constant H01 => 0x0101010101010101;
  my $x = $x0;
  $x -= ($x >> 1) & M1;
  $x = ($x & M2) + (($x >> 2) & M2);
  $x = ($x + ($x >> 4)) & M4;
  return ($x * H01) >> 56;
}

sub sortbyonebits($a) {
  my %c = map {$_ => popcount64($_)} @{$a};
  return [sort {$c{$::a} <=> $c{$::b} || $::a <=> $::b} @{$a}];
}

The only language I've added since then is Crystal, which has a built-in popcount method for its integers.

Full code on github.

See also:
The Weekly Challenge 238: Running Persistence
The Weekly Challenge 258: Valuing the Count

Add A Comment

Your Name
Your Email
Your Comment

Your submission will be ignored if any field is left blank, but your email address will not be displayed. Comments will be processed through markdown.

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