RogerBW's Blog

The Weekly Challenge 337: The Odd Current 07 September 2025

I’ve been doing the Weekly Challenges. The latest involved array analysis and matrix incrementing. (Note that this ends today.)

Task 1: Smaller Than Current

You are given an array of numbers, @num1.

Write a script to return an array, @num2, where $num2[i] is the count of all numbers less than or equal to $num1[i].

My visualisation of this is: if the list is sorted into ascending order, the number of items strictly less than any value is the index of that value's first occurrence. Thus for example with first occurrences in bold:

index 0 1 2 3
value 1 2 2 3

So step 1 is to create a sorted copy of the list; step 2 is to drop the appropriate index values into a hash; and step 3 is to take the original list, map each value to its hash entry, and return the result. In Perl:

sub smallerthancurrent($a) {

Make the sorted copy of the list.

  my @b = sort {$::a <=> $::b} @{$a};
  my %m;

Step through the sorted list.

  while (my ($i, $v) = each @b) {

If there's no hash entry for that value, create it.

    unless (exists $m{$v}) {
      $m{$v} = $i;
    }
  }

Read out the hash value for each member of the original list.

  return [map {$m{$_}} @{$a}];
}

Task 2: Odd Matrix

You are given row and col, also a list of positions in the matrix.

Write a script to perform action on each location (0-indexed) as provided in the list and find out the total odd valued cells.

For each location (r, c), do both of the following:

a) Increment by 1 all the cells on row r. b) Increment by 1 all the cells on column c.`

The obvious way of doing this is to spin up the actual matrix and increment the values.

But, and I admit this was after I had written that code (in all twelve languages) I had an idea. First of all let's ignore the actual values and just say that in the end state a given cell is "flipped" (incremented 1, 3, 5, ... times) or "un-flipped" (incremented 0, 2, 4, ... times).

Consider a matrix of known size with known numbers of flipped rows and flipped columns. Each row contributes a flipped cell for each un-flipped column, and each column contributes a flipped cell for each un-flipped row. (The intersections would be double-counted, but since by definition they aren't ever flipped that doesn't matter.)

So all I need to construct from the list of points is the liara of flipped rows and columns in the final configuration.

This isn't a great deal shorter in lines of code than working through the process in full, but it should run rather faster since there's no nested loop of rows and columns; it removes the need to allocate and scan the whole matrix, which would be significant if the code were to be applied to more than trivial problems.

Scala:

def oddmatrix(rows: Int, cols: Int, points: List[List[Int]]): Int = {

Construct sets, to track which rows and which columns are flipped.

  var rm = mutable.Set.empty[Int]
  var cm = mutable.Set.empty[Int]

Iterate through the points.

  for (p <- points) {

If this row is already flipped, remove it from the row set to count it as un-flipped.

    if (rm.contains(p(0))) {
      rm -= p(0)

Otherwise, add it to the set to count it as flipped.

    } else {
      rm += p(0)
    }

Do the same for the column flip.

    if (cm.contains(p(1))) {
      cm -= p(1)
    } else {
      cm += p(1)
    }
  }

Then simply read out (flipped rows × un-flipped columns) + (flipped columns × un-flipped rows).

  rm.size * (cols - cm.size) +
  cm.size * (rows - rm.size)
}

Full code on github.

Add A Comment

Your Name
Your Email
Your Comment

Note that I will only approve comments that relate to the blog post itself, not ones that relate only to previous comments. This is to ensure that the blog remains outside the scope of the UK's Online Safety Act (2023).

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 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 disaster 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 horrorm science fiction hugo 2014 hugo 2015 hugo 2016 hugo 2017 hugo 2018 hugo 2019 hugo 2020 hugo 2021 hugo 2022 hugo 2023 hugo 2024 hugo 2025 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 openscad opera parody paul temple perl perl weekly challenge photography podcast poetry politics postscript powers prediction privacy project woolsack pyracantha python quantum rail raku ranting raspberry pi reading reading boardgames social real life restaurant review 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 typst 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