RogerBW's Blog

The Weekly Challenge 189: Degree of Character 06 November 2022

I’ve been doing the Weekly Challenges. The latest involved filtering character lists and finding subarrays. (Note that this is open until 6 November 2022.)

Task 1: Greater Character

You are given an array of characters (a..z) and a target character.

Write a script to find out the smallest character in the given array lexicographically greater than the target character.

We establish from the examples that if no character in the array is greater than the target, we return the target. Therefore:

sub greatercharacter($a, $k) {
  my @aa = sort grep {$_ gt $k} @{$a};
  if (@aa) {
    return $aa[0];
  } else {
    return $k;
  }
}

In PostScript I use the convention that individual characters of strings are represented as integers and use those internally, converting back to a string at the end.

/greatercharacter {
    1 dict begin
    0 get /k exch def
    { 0 get } map { k gt } filter
    [ exch
      dup length 0 gt {
          quicksort 0 get
      } {
          pop
          k
      } ifelse
    ] a2s
    end
} bind def

(map, filter, quicksort and a2s are from my PostScript libraries.)

Task 2: Array Degree

You are given an array of 2 or more non-negative integers.

Write a script to find out the smallest slice, i.e. contiguous subarray of the original array, having the degree of the given array.

The degree of an array is the maximum frequence of an element in the array.

This is the sort of fiddly data structure manipulation that I mostly learned in Perl, and it's very good for me to work it out in other languages too. Overall:

  • I build a frequency map f of the values in the array. The highest value in that is the degree. I only care about numbers which occur that many times.

  • I build an inverse location table, telling me where each number is to be found. In example 5's [2, 1, 2, 1, 1], this would be {1 => [1, 3, 4], 2 => [0, 2]}. (Since I only care about first and last values, for some of the languages I make this explicitly a two-element list.)

  • I then look through all the numbers that occur (degree) times, and generate a length from inverse: position of the last occurrence, minus position of the first occurrence, plus one for the fencepost. If that length is smaller than the smallest length I've seen, store it and the relevant indices.

  • Finally return the array slice defined by those indices.

In Kotlin:

fun arraydegree(a: List<Int>): List<Int> {

Build the frequency map and calculate the degree:

    var f = mutableMapOf<Int, Int>()
    for (x in a) {
        if (f.containsKey(x)) {
            f[x] = f[x]!! + 1
        } else {
            f[x] = 1
        }
    }
    val degree = f.values.maxOrNull()!!

Build the inverse location table:

    var inverse = mutableMapOf<Int, MutableList<Int>>()
    for ((i, x) in a.withIndex()) {
        if (inverse.containsKey(x)) {
            inverse[x]!!.add(i)
        } else {
            inverse[x] = mutableListOf(i)
        }
    }

Iterate through each number that exists in the correct degree, working out the length of the subarray including its first and last positions, and store those positions if it'll be shorter than any previously calculated length.

    var minlen = 1 + a.size
    var se = listOf(0, 1)
    for (n in f.keys) {
        if (f[n]!! == degree) {
            val ll = 1 + inverse[n]!![inverse[n]!!.size-1] - inverse[n]!![0]
            if (ll < minlen) {
                minlen = ll
                se = listOf(inverse[n]!![0], inverse[n]!![inverse[n]!!.size-1])
            }
        }
    }

Finally return the array slice.

    return a.slice(se[0]..se[1])
}

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