RogerBW's Blog

The Weekly Challenge 238: Running Persistence 15 October 2023

I’ve been doing the Weekly Challenges. The latest involved cumulative sums and complicated sorts. (Note that this ends today.)

Task 1: Running Sum

You are given an array of integers.

Write a script to return the running sum of the given array. The running sum can be calculated as sum[i] = num[0] + num[1] + …. + num[i].

There are two fairly obvious ways to do this. One is to start an accumulator at zero, add each entry, and copy the running total into a new list. That let me do it variable-free in PostScript:

/runningsum {

Push onto the stack, below the input array, the opening of a new array and a single member of velue zero.

    [ exch
      0 exch

For each member of the input array, add to the latest member of the new, and make another copy, which we'll add to with the next element.

      {
          add dup
      } forall

The last entry will be duplicated, so drop that.

      pop

And end the array.

    ]
} bind def

But in other languages I made a copy of the input list and just added to each member (after the first) the value of the previous member. Thus in Raku:

sub runningsum(@a) {
    my @b = @a;
    for 1 .. @a.end -> $i {
        @b[$i] += @b[$i-1];
    }
    return @b;
}

Task 2: Persistence Sort

You are given an array of positive integers.

Write a script to sort the given array in increasing order with respect to the count of steps required to obtain a single-digit number by multiplying its digits recursively for each array element. If any two numbers have the same count of steps, then print the smaller number first.

So there are two parts to this. One is a function to generate the persistence value, which is fairly straightforwawrd. Rust:

fn persistence(a: u32) -> u32 {
    let mut steps = 0;
    let mut b = a;
    while b > 9 {
        steps += 1;
        let mut p = 1;
        while b > 0 {
            p *= b % 10;
            b /= 10;
        }
        b = p;
    }
    steps
}

Then it's a two-stage sort, by persistence value and then by individual value, and different languages approach this in different ways. In Rust again, sort() is stable, and there's a sort_by_cached_key() which takes care of not calculating persistence more often than we have to. (While it doesn't matter with these small examples, it could clearly get quite expensive.)

fn persistencearray(a: Vec<u32>) -> Vec<u32> {
    let mut b = a;
    b.sort();
    b.sort_by_cached_key(|i| persistence(*i));
    b
}

Kotlin and Python also have stable sorting, but get a manual cache of persistence values. In Lua and most of the other languages, I build a manual cache and then do a sort with a custom comparator.

function persistencearray(a)
   local b = a

Build the cache (avoiding duplications):

   local c = {}
   for _, v in ipairs(b) do
      if c[v] == nil then
         c[v] = persistence(v)
      end
   end

Sort with comparator:

   table.sort(b, function(a, b)
                 if c[a] == c[b] then
                    return a < b
                 else
                    return c[a] < c[b]
                 end
   end)
   return b
end

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