RogerBW's Blog

The Weekly Challenge 154: Missing Padovan 03 March 2022

I’ve been doing the Weekly Challenges. The latest involved permutations and primality testing. (Note that this is open until 6 March 2022.)

Task 1: Missing Permutation

You are given possible permutations of the string 'PERL'.

Write a script to find any permutations missing from the list.

My basic approach is to make a list of all possible permutations (of the first argument in the list, rather than making it specific to one string), then delete from it those in the input list.

A fairly sharp dividing line separates the languages with some sort of built-in permutation engine (Python, Ruby, Raku) or readily-available module (Perl, Rust) and those without (the latter being PostScript, JavaScript, Kotlin and Lua). For those last I wrote a non-recursive implementation of Heap's Algorithm (dodging about a bit for Lua with its 1-based pseudo-arrays). For the others it was rather easier. The cleanest code is probably Python with itertools:

def missingpermutations(lst):
  perms=set("".join(x) for x in permutations(lst[0]))
  for x in lst:
    perms.discard(x)
  return list(perms)

But just for fun here's a permutor in PostScript:

/permute { % [array] {proc} permute runs proc on each permutation of array
    7 dict begin
    /subproc exch def
    /a exch def
    /n a length def
    /c [ n { 0 } repeat ] def
    mark a subproc cleartomark
    /i 0 def
    {
        i n ge {
            exit
        } if
        c i get i lt {
            i 2 mod 0 eq {
                0 i permute.swap
            } {
                c i get i permute.swap
            } ifelse
            mark a subproc cleartomark
            c i get 1 add c exch i exch put
            /i 0 def
        } {
            c i 0 put
            /i i 1 add def
        } ifelse
    } loop
    end
} bind def

/permute.swap {
    /bi exch def
    /ai exch def
    a ai get
    a bi get
    a exch ai exch put
    a exch bi exch put
} bind def

Task 2: Padovan Prime

A Padovan Prime is a Padovan Number that's also prime.

In number theory, the Padovan sequence is the sequence of integers P(n) defined by the initial values.

P(0) = P(1) = P(2) = 1

and then followed by

P(n) = P(n-2) + P(n-3)

Write a script to compute first 10 distinct Padovan Primes.

Opinions differ; Wikipedia quotes this definition, while the OEIS starts its system with (1, 0, 0). But 0 and 1 are canonically non-prime anyway.

With Raku I was able to use its lazy sequence generator:

sub padovanprime($ct) {
    my $pp=SetHash.new;
    for (1, 1, 1, -> $a, $b, $c { $a + $b } ... *) -> $padovan {
        if (isprime($padovan)) {
            $pp{$padovan}=True;
            if $pp.elems >= $ct {
                last;
            }
        }
    }
    return [$pp.keys.sort];
}

But, sadly, not to rely on the built-in and quite fast is-prime function. This will reliably return false if the number is known not to be prime, but returns true for either a prime or a number with unknown primality. (Perl's Math::Prime::Util at least has a three-state return for (no, unknown, yes).) With numbers of this size it probably won't matter, but as a result I imported the primality-testing code I'd written for other languages.

(Normally I'd use a sieve of Eratosthenes as in previous Challenges, but since I don't know in advance how large the numbers will be I fall back on lightly-optimised trial division.)

sub isprime($candidate) {

Check the easy cases first.

    if (!is-prime($candidate)) {
        return False;
    } elsif ($candidate==2) {
        return True;
    } elsif ($candidate==3) {
        return True;
    } elsif ($candidate % 2 == 0) {
        return False;
    } elsif ($candidate % 3 == 0) {
        return False;
    }

Failing that, start checking divisors of the form 6n±1 until we either exceed the square root of the candidate or find an even divisor.

    my $anchor=0;
    my $limit=floor(sqrt($candidate));
    while (True) {
        $anchor+=6;
        for ($anchor-1,$anchor+1) -> $t {
            if ($t > $limit) {
                return True;
            }
            if ($candidate % $t == 0) {
                return False;
            }
        }
    }
}

Although this is basically the same code I'd written for other languages, it was desperately slow in Raku, reliably taking about 58s to complete the test cases on my unloaded reference machine. Optimised compiled Rust took 0.2s; Kotlin took 0.45s even with Java runtime startup; Javascript under Node, 0.8s; Ruby, 1.4s; Rust unoptimised including compilation time 1.5s; Lua, 1.9s; Perl, 3.2s; Python, 6.7s, PostScript, 7.0s.

(Yeah, one might start to think that Rust is actually not a terrible scripting language…)

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