RogerBW's Blog

The Weekly Challenge 302: Step By Step One Becomes Zero 05 January 2025

I’ve been doing the Weekly Challenges. The latest involved string searching and sequence analysis. (Note that this ends today.)

Task 1: Ones and Zeroes

You are given an array of binary strings, @str, and two integers, $x and $y.

Write a script to return the size of the largest subset of @str such that there are at most $x 0s and $y 1s in the subset.

A set m is a subset of n if all elements of m are also elements of n.

That the strings are binary is unimportant; all that matters is how many of each character they contain. So the first stage is to build up a list of that; the second is to search all possible combinations to see which contains most elements and complies with the limits. In Rust:

fn onesandzeroes(a: Vec<&str>, zeroes: usize, ones: usize) -> usize {

Build the list of (zeroes, ones) corresponding to the input list.

    let mut ax = Vec::new();
    for ns in a {
        let mut o = 0;
        let mut n = 0;
        for c in ns.chars() {
            match c {
                '0' => { o += 1; },
                '1' => { n += 1; },
                _ => panic!("Bad digit"),
            };
        }
        ax.push((o, n));
    }
    let mut mx = 0;

Search each possible combination. (Some languages have a combinations generator that can restrict the number of items searched, but I didn't bother for this - it's just a bitmask to select all possible combinations of one or more values from the list.)

    for mask in 1 .. (1 << ax.len()) {
        let mut o = 0;
        let mut n = 0;
        let mut ct = 0;
        for (i, x) in ax.iter().enumerate() {

If this entry matches the mask, count its ones and zeroes and bail out if there are too many overall.

             if mask & (1 << i) > 0 {
                o += x.0;
                n += x.1;
                ct += 1;
                if o > zeroes || n > ones {
                    break;
                }
            }

If this is a valid combination, re-set the maximum value.

            if o <= zeroes && n <= ones {
                mx = std::cmp::max(mx, ct);
            }
        }
    }
    mx
}

Task 2: Step by Step

You are given an array of integers, @ints.

Write a script to find the minimum positive start value such that step by step sum is never less than one.

The answer is clearly 1 minus the lowest value the progressive sum achieves (and at least 1). Raku:

sub stepbystep(@a) {

Set initial minimum value and progressive sum.

    my $mv = 0;
    my $tot = 0;

Iterate over the sequence, calculating the progressive sum and latching the lowest value seen.

    for @a -> $s {
        $tot += $s;
        if ($mv > $tot) {
            $mv = $tot;
        }
    }

Then turn that into the answer.

    1 - $mv;
}

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