RogerBW's Blog

The Weekly Challenge 228: The Empty Sum 06 August 2023

I’ve been doing the Weekly Challenges. The latest involved inspecting integer elements and making iterative things less so. (Note that this ends today.)

Task 1: Unique Sum

You are given an array of integers.

Write a script to find out the sum of unique elements in the given array.

Fairly straightforward: convert the list into a hash with values equal to the count of elements. Raku has a Bag structure that's good for this, and Rust has the Counter crate that I've been using a great deal lately. Ruby, Kotlin and Python have hashes with defaults. Perl has autovivification, which is almost as good but rather less flexible. (Which just leaves Javascript, Lua and PostScript where I have to write it out the long way.)

Then take all the entries where count = 1, and sum them. Perl:

sub uniquesum($a) {
  my %c;
  map {$c{$_}++} @{$a};
  return sum0(grep {$c{$_} == 1} keys %c);
}

I like the explicitness of thw two stages in the Rust version.

fn uniquesum(a: Vec<u32>) -> u32 {

Break down the list into a Counter.

    let c = a.into_iter().collect::<Counter<u32>>();

Filter the object for count = 1, then output the values.

    c.iter().filter(|(_k, v)| **v == 1usize).map(|(k, _v)| k).sum()
}

Task 2: Empty Array

You are given an array of integers in which all elements are unique.

Write a script to perform the following operations until the array is empty and return the total count of operations.

If the first element is the smallest then remove it otherwise move it to the end.

Well.

I mean, I could do that. With a ring buffer or something.

Or I could say, well, we're basically counting the number of passes it takes to get the lowest value in the list to the front of the list, aren't we? So let's just work that out based on where it is in the list. And iterate for each number.

(There may be inputs for which this approach doesn't work. But it was fun to write.)

In Lua (where for once the 1-based list indices are actually useful):

function emptyarray(a0)
   local t = 0
   local a = a0
   while #a > 0 do

Find the minimum value.

      local mn = math.min(table.unpack(a))

Locate the minimum in the list.

      for i, v in ipairs(a) do
         if v == mn then

Remove it and count the number of "operations" needed to get here.

            table.remove(a, i)
            t = t + i
            break
         end
      end
   end
   return t
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 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