RogerBW's Blog

The Weekly Challenge 294: Permutationally Consecutive 10 November 2024

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

Task 1: Consecutive Sequence

You are given an unsorted array of integers, @ints.

Write a script to return the length of the longest consecutive elements sequence. Return -1 if none found. The algorithm must runs in O(n) time.

Exhaustive search of the sorted array seems to be the trick here. In Raku:

sub consecutivesequence(@a) {

Get the sorted array and initialise various counters.

    my @b = @a.sort({$^a <=> $^b});
    my $mxlen = 0;
    my $here = 0;
    loop {

Look from one entry after the current ($here), to potentially as far as the end.

        for ($here + 1) .. @b.end -> $there {

If it isn't part of the sequence that started at $here, note that sequence and start from this point next time..

            if @b[$there] != $there - $here + @b[$here] {
                $mxlen = max($mxlen, $there - $here);
                $here = $there;
                last;
            }

If we got to the end without a non-sequence number, note that.

            if $there == @b.end {
                $mxlen = max($mxlen, $there - $here + 1);
                $here = $there;
                last;
            }
        }

If we've got to the end, exit.

        if $here >= @b.end {
            last;
        }
    }

And if the longest sequence is 1 (every number on its own is a sequence of 1), return -1 as requested.

    if $mxlen < 2 {
        $mxlen = -1;
    }
    $mxlen;
}

Task 2: Next Permutation

You are given an array of integers, @ints.

Write a script to find out the next permutation of the given array.

The next permutation of an array of integers is the next lexicographically greater permutation of its integer.

In the languages with built-in permutation routines, that's the order in which they produce them, but the routine I wrote implementing Heap's algorithm doesn't… so I sort the result.

Rust, which does have a permuter:

use itertools::Itertools;

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

Start with a sorted copy of the list.

    let mut b = a.clone();
    b.sort();
    let mut flag = false;
    let mut out: Vec<u32> = Vec::new();

Look through the permutations.

    for px in b.iter().permutations(b.len()) {
        let py = px.iter().copied().copied().collect::<Vec<u32>>();

If we don't have a result at all, stick in the first one. (Because we're only going to look through this list once.)

        if out.len() == 0 {
            out = py.clone();
        }

If the previous pass set the flag, use this result.

        if flag {
            out = py.clone();
            break;
        }

If we have a match, set the flag for the next pass.

        if py == a {
            flag = true;
        }
    }
    out
}

So most of the time the loop finds a match to the input, sets the flag, then on the next loop sets the next entry. But if the match was on the last entry, that won;t work, so we pre-seed the output with the first entry.

Kotlin needs a sorter, which ends up looking like:

    val listComparator = Comparator {
        i: List<Int>, j: List<Int> ->
            var ix = 0
        var res = false
        while (true) {
            if (ix >= i.size && ix >= j.size) {
                break
            }
            if (ix < i.size && ix >= j.size) {
                res = true
                break
            }
            if (ix >= i.size && ix < j.size) {
                res = false
                break
            }
            if (i[ix] != j[ix]) {
                res = i[ix] < j[ix]
                break
            }
            ix += 1
        }
        if (res) {
            -1
        } else {
            1
        }
    }
    for (px in permute(b).sortedWith(listComparator)) {

(etc. as before)

Full code on github.


  1. Posted by Dave at 09:59am on 11 November 2024

    REPLACEME_DESC - something gone wrong with your publishing script ?

    Doesn't use of sort() voilate the O(n) requirement ?

  2. Posted by RogerBW at 12:00pm on 12 November 2024

    Not so much a publishing script as me remembering to fill in the blanks.

    I hadn't spotted the O(1) constraint and I suspect it may not be possible, My code is O(1) on the sorted list, but I can't see a way to get "is there a number one higher than this", for each number in an unsorted list, that will run in O(1).

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