RogerBW's Blog

The Weekly Challenge 257: Smaller than Echelon 25 February 2024

I’ve been doing the Weekly Challenges. The latest involved list processing and matrix testing. (Note that this ends today.)

Task 1: Smaller than Current

You are given a array of integers, @ints.

Write a script to find out how many integers are smaller than current i.e. foreach ints[i], count ints[j] < ints[i] where i != j.

There's an obvious O(n²) way of doing this, but I thought it was cleaner to sort.

Scala:

  def smallerthancurrent(a: List[Int]): List[Int] = {

Set up a sorted list of inputs, and a map that'll contain the solution.

    val s: List[Int] = a.sortWith(_ < _)
    var l = mutable.Map.empty[Int, Int]

For each item in the sorted list, store the index, which is the number of items smaller than that. (Use the first occurrence of the item; I added the test case with a duplicate value.)

    for ((n, i) <- s.zipWithIndex) {
      if (!l.contains(n)) {
        l += (n -> i)
      }
    }

Then just read off the values in the order of the original list.

    a.map { n => l(n) }.toList
  }

Task 2: Reduced Row Echelon

Given a matrix M, check whether the matrix is in reduced row echelon form.

A matrix must have the following properties to be in reduced row echelon form:

  1. If a row does not consist entirely of zeros, then the first nonzero number in the row is a 1. We call this the leading 1.

  2. If there are any rows that consist entirely of zeros, then they are grouped together at the bottom of the matrix.

  3. In any two successive rows that do not consist entirely of zeros, the leading 1 in the lower row occurs farther to the right than the leading 1 in the higher row.

  4. Each column that contains a leading 1 has zeros everywhere else in that column.

I propsed a bunch of the test cases here because I wanted to test each rule individually. Raku:

sub reducedrowechelon(@a) {

We'll be using the position of the first 1 in each row quite a bit. That goes in @leadingone.

    my @leadingone;

Inspect each row:

    for @a -> @row {

Set the leading-one position to -1, indiciating no 1 found.

        my $lp = -1;

For each item in the row:

        for 0 .. @row.end -> $cn {
            my $cell = @row[$cn];

If it's a 1, store that position and exit.

            if ($cell == 1) {
                $lp = $cn;
                last;

If it's not a zero, bail out (rule 1).

            } elsif ($cell != 0) {
                return False;
            }
        }

Add this row's leading-one position to the list.

        @leadingone.push($lp);
    }

If there are trailing rows of all-zero, ignore them.

    while (@leadingone[*-1] == -1) {
        @leadingone.pop;
    }

Now sort the remaining leading-one positions.

    my @c = @leadingone.sort({$^a <=> $^b});

If there are any all-zero rows, they weren't trailing. Bail out by rule 2.

    if (@c[0] == -1) {
        return False;
    }

If the sorted list doesn't match the original, the leading ones aren't progressively to the right. Bail out by rule 3.

    if (!(@c eqv @leadingone)) {
        return False;
    }

Finally take a columnwise slice of each column that has a leading 1 in it. Test for 1s and 0s in the right places (rule 4).

    for @c -> $i {
        my @col = @a.map({$_[$i]}).sort({$^a <=> $^b});
        if (@col[*-1] != 1 ||
            @col[*-2] != 0 ||
            @col[0] != 0) {
            return False;
        }
    }
    return True;
}

I spot two possible problems here:

(1) the rule-3 test will pass two leading-ones of equal value. But the rule-4 test will remove those because they won't be unique in the column. I'd rather rule 3 be fully tested in its own segment of the codex.

(2) the rule-4 test should reject a negative value found in the same column as a leading 1 (@col[0] != 0 above). The existing test cases don't fail in that case (this is my fault since I proposed most of them).

Full code on github.

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