RogerBW's Blog

The Weekly Challenge 244: Counting Your Heroes 26 November 2023

I’ve been doing the Weekly Challenges. The latest involved a list search and combinations. (Note that this ends today.)

Task 1: Count Smaller

You are given an array of integers.

Write a script to calculate the number of integers smaller than the integer at each index.

Well, you could just search the array repeatedly. But that seemed dull. In Rust:

fn countsmaller(nums: Vec<u32>) -> Vec<u32> {

b is a sorted copy of the input list.

    let mut b = nums.clone();
    let mut sm: HashMap<u32, u32> = HashMap::new();

l is the latest number we've seen.

    let mut l = 0;
    for (i, e) in b.iter().enumerate() {

If we're looking at the first value, or the value here isn't the same as the last value we saw…

        if i == 0 || *e != l {

The number of values less than it equals its index in the sorted list.

            sm.insert(*e, i as u32);

And update the last value seen.

            l = *e;

Then map out the original list to the values hash.

    nums.into_iter().map(|n| *sm.get(&n).unwrap()).collect::<Vec<u32>>()

Task 2: Group Hero

You are given an array of integers representing the strength.

Write a script to return the sum of the powers of all possible combinations; power is defined as the square of the largest number in a sequence, multiplied by the smallest.

So clearly we're going to have to calculate all possible combinations, for which in Perl I'll use Algorithm::Combinatorics as usual.

sub grouphero($nums0) {

Finding an algorithm that preserves the order makes this easy: just do one big sort at the start.

  my @nums = sort {$a <=> $b} @{$nums0};
  my $sum = 0;

For each possible combination length, then for each possible combination of that length…

  foreach my $l (1 .. scalar @nums) {
    foreach my $c (combinations(\@nums, $l)) {

Add (highest squared) * (lowest).

      $sum += $c->[-1] * $c->[-1] * $c->[0];
  return $sum;

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.

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