RogerBW's Blog

The Weekly Challenge 221: Good Arithmetic 18 June 2023

I’ve been doing the Weekly Challenges. The latest involved more finding strings that can be made out of letters, and a search for a subsequence. (Note that this is open until 18 June 2023.)

I've been away on holiday, so I only did this in my favourite extra languages (Rust and PostScript) rather than the usual full set.

Task 1: Good Strings

You are given a list of @words and a string $chars.

A string is good if it can be formed by characters from $chars, each character can be used only once.

Write a script to return the sum of lengths of all good strings in words.

Clearly I'll use word2map from challenge #216 task 2, which breaks down a word into a hash of letters and their frequencies.

Rust benefits from the Counter class (in effect a hash with a default value of zero):

use counter::Counter;

fn word2map(word: &str) -> Counter<char> {
    let mut m: Counter<char> = Counter::new();
    for c in word.to_ascii_lowercase().chars() {
        if c >= 'a' && c <= 'z' {
            m[&c] += 1;
        }
    }
    m
}

fn goodstrings(words: Vec<&str>, chars: &str) -> u32 {
    let mut out: u32 = 0;

Get a map of the available letters.

    let cm = word2map(chars);
    for w in words {
        let f = word2map(w);
        let mut valid = true;

For each letter in the candidate word

        for c in f.keys() {

If more are needed than are available, bail out.

            if f.get(c) > cm.get(c) {
                valid = false;
                break;
            }
        }

Otuerwise it's valid, so add its length to the output list.

        if valid {
            out += w.len() as u32;
        }
    }
    out
}

Task 2: Arithmetic Subsequence

You are given an array of integers, @ints.

Write a script to find the length of the longest Arithmetic Subsequence in the given array.

A subsequence is an array that can be derived from another array by deleting some or none elements without changing the order of the remaining elements.

A subsquence is arithmetic if ints[i + 1] - ints[i] are all the same value (for 0 <= i < ints.length - 1).

My approach here is a depth-first search. For each sequence on the stack (starting with the input sequence), return its length if it's a valid arithmetic sequence; otherwise, push onto the stack a set of sequences each consisting of this sequence with one entry removed.

(This is quick and dirty so it assumes there will be a non-trivial arithmetic subsequence to be found.)

In Raku, I start with a test for arithmetic sequentiality:

sub isas(@a) {
    my $t = @a[1] - @a[0];
    for @a.skip(1).rotor(2 => -1) -> $i {
        if ($i[1] - $i[0]) != $t {
            return False;
        }
    }
    return True;
}

Then the depth-first search.

sub arithmeticsubsequence(@ints) {

Put the input on the stack.

    my @stack = [ @ints, ];
    while (@stack.elems > 0) {

Pull a sequence off the stack.

        my @t = @stack.shift.List;

If it's arithmetic, return its length.

        if (isas(@t)) {
            return @t.elems;
        } else {

Otherwise, for each entry in it that I might remove,

            for (0 .. @t.end) -> $i {

build a new sequence omitting that entry (this is surprisingly hard to do elegantly)

                my @tt;
                for (0 .. @t.end) -> $ix {
                    if ($i != $ix) {
                        @tt.push(@t[$ix]);
                    }
                }

and push it onto the stack for later testing.

                @stack.push(@tt);
            }
        }
    }
    return 0;
}

This automatically gets me tests of the full sequence, full sequence missing one entry, full missing two, etc.; it's not particularly efficient, because it'll test subsequences multiple times, but at least the test exits early on failure.

Full code on github.

See also:
The Weekly Challenge 216: Word Registration

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