RogerBW's Blog

The Weekly Challenge 304: Binary to the Maxmim 19 January 2025

I’ve been doing the Weekly Challenges. The latest involved substitution and windowing. (Note that this ends today.)

Task 1: Arrange Binary

You are given a list of binary digits (0 and 1) and a positive integer, $n.

Write a script to return true if you can re-arrange the list by replacing at least $n digits with 1 in the given list so that no two consecutive digits are 1 otherwise return false.

The simplest approach seemed to be to try it and see: look through the list, and if I can validly insert a 1, do so. Kotlin:

fun arrangebinary(a: List<Int>, n: Int): Boolean {

Copy the list and initialise the counter.

    var b = ArrayList(a)
    var t = n

Look through the list. for (i in 0 .. b.size - 1) {

If this place's value is a zero, and

        if (b[i] == 0 &&

We're at the start, or the previous place's value was a zero, and

            (i == 0 || b[i - 1] == 0) &&

We're at the end, or the next place's value is a zero

            (i == b.size - 1 || b[i + 1] == 0)) {

Then insert a 1 and decrement the counter.

            b[i] = 1
            t -= 1
        }
    }

Reteurn true of we reached zero.

    return t <= 0
}

Task 2: Maximum Average

You are given an array of integers, @ints and an integer, $n which is less than or equal to total elements in the given array.

Write a script to find the contiguous subarray whose length is the given integer, $n, and has the maximum average. It should return the average.

Mostly this is a job for sliding windows, and most languages have that available (thouh the Perl one in List::MoreUtils can be a bit rough).

use List::Util qw(sum max);
use List::MoreUtils qw(slideatatime);

sub maximumaverage($a, $n) {
  my $mx = 0;
  my $dd = slideatatime 1, $n, @{$a};
  while (my @s = $dd->()) {
    if (scalar @s == $n) {
      $mx = max($mx, sum(@s));
    }
  }
  $mx / $n;
}

But JavaScript, for example, doesn't have a built-in sliding window, so instead I take a running sum.

function maximumaverage(a, n) {
    let t = 0;
    for (let i = 0; i < n; i += 1) {
        t += a[i];
    }

Then add the new value and subtract the old one, keeping the maximum.

    let mx = t;
    for (let i = n; i < a.length; i += 1) {
        t += a[i];
        t -= a[i - n];
        mx = Math.max(mx, t);
    }
    return mx / n
}

In both cases, the icky floating point bit happens right at the end.

Full code on github.

Add A Comment

Your Name
Your Email
Your Comment

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