RogerBW's Blog

The Weekly Challenge 202: Consecutive Valley 05 February 2023

I’ve been doing the Weekly Challenges. The latest involved various sorts of list filtering. (Note that this closes today.)

Task 1: Consecutive Odds

You are given an array of integers.

Write a script to print 1 if there are THREE consecutive odds in the given array otherwise print 0.

For every language except Perl, I turn that to true/false, because why not? The logic is the same across all languages. Raku:

sub consecutiveodds(@a) {

Set up the odds counter.

    my $i = 0;

For each number in the sequence,

    for (@a) -> $v {

if it's odd,

        if ($v % 2 == 1) {

I have one more odd-in-sequence than I did last time.


If I have three odds-in-sequence,

            if ($i >= 3) {

stop here.

                return True;

If it isn't odd,

        } else {

I have no odds-in-sequence.

            $i = 0;

And if I never got to three having run off the end of the list, return the other result.

    return False;

Another approach would be to mod2 the whole list, then take three-element windows onto it and check them individually, but I find the above pretty straightforward and reasonably efficient.

Task 2: Widest Valley

Given a profile as a list of altitudes, return the leftmost widest valley. A valley is defined as a subarray of the profile consisting of two parts: the first part is non-increasing and the second part is non-decreasing. Either part can be empty.

The logic is a bit less obvious than some of these problems have been. Here's my Rust version, which falls into three stages.

fn widestvalley(a: Vec<usize>) -> Vec<usize> {

First, look through the list and combine consecutive multiples into (value, count) tuples. (Well, if I were writing only in Rust I'd probably use tuples; here for portability I just have separate vectors av and ac.)

    let mut av = Vec::new();
    let mut ac = Vec::new();
    let mut l = 0;
    for &v in &a {
        if v == l {
            *ac.last_mut().unwrap() += 1;
        } else {
            l = v;

Then I go looking for valley starts and ends - i.e. isolated highest points. The first and last distinct values always count as these; so does any value higher than both its neighbours. (Beware of languages that don't have short-circuiting evaluation, such as Lua and PostScript, because the offset indices won't be valid.) The start value of such a point is the index in a of the first such value in its group; the end value is the index of the last. (c is therefore the index into a that we're artificially incrementing.)

    let mut s = Vec::new();
    let mut e = Vec::new();
    let mut c = 0;
    for i in 0..=av.len() - 1 {
        if i == 0
            || i == av.len() - 1
            || (av[i - 1] < av[i] && av[i] > av[i + 1])
            e.push(c + ac[i] - 1);
        c += ac[i];

Finally, each valley runs from an s-value to the next e-value (i.e. including the full width of both peaks). Look through each of these, and if it's wider than we've had before, make it the output.

    let mut out = Vec::new();
    for i in 0..=s.len() - 2 {
        if e[i + 1] - s[i] + 1 > out.len() {
            out = a[s[i] ..= e[i+1]].to_vec();

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