RogerBW's Blog

The Weekly Challenge 288: Block the Palindrome 29 September 2024

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

Task 1: Closest Palindrome

You are given a string, $str, which is an integer.

Write a script to find out the closest palindrome, not including itself. If there are more than one then return the smallest.

The closest is defined as the absolute difference minimized between two integers.

One could probably solve many cases of this by reversing the first half of the string onto the second half, e.g. 456 → 454, but there are exceptions—such as the test case of 1000, for which 1001 is a palindrome but not the correct answer.

So instead I perform a search with deltas -1, +1, -2, +2, etc. Kotlin:

fun closestpalindrome(a: String): String {

Get the int value of the string.

    val n = a.toInt()

Initialise the delta and start an infinite loop.

    var delta = -1
    while (true) {

Work out the next candidate value, and stringify it.

        val q = (n + delta).toString()

If it's a palindrome, return it.

        if (q == q.reversed()) {
            return q
        }

Otherwise, flip the sign on the delta, and if it's now negative subtract one.

        delta = -delta;
        if (delta < 0) {
            delta -= 1
        }
    }
}

It would be equally valid to have nested loops, an outer for (1, 2, 3, …) and an inner for (-1, +1) and multiply them together, but this felt cleaner.

Task 2: Contiguous Block

You are given a rectangular matrix where all the cells contain either x or o.

Write a script to determine the size of the largest contiguous block.

A contiguous block consists of elements containing the same symbol which share an edge (not just a corner) with other elements in the block, and where there is a path between any two of these elements that crosses only those shared edges.

The main concern here is: can an array be a hash key? Because I want to keep track of whether coordinates have been visited. Generally a mutable array can't be used as a key (what happens if it changes?) but a fixed one can. In languages where that wasn't available or I didn't sufficiently understand how it was done, I wrote an encoder.

Thus in Raku, where I assume an arbitrary value greater than grid size:

sub cencode($x, $y) {
    return Int($x * 1000000 + $y);
}

This was a lot of work to get right. They're integers going in, they're being subjected to integer-only operations, why wouldn't they be integers coming out?

sub cdecode($c) {
    return [Int(($c+0) div 1000000), Int($c % 1000000)];
}

sub contiguousblock(@a) {

Establish the grid sizes.

    my $y = @a.elems;
    my $x = @a[0].elems;

Initialise the set of possible start points to all grid points.

    my %starts = SetHash.new;
    for (0 .. $x - 1) -> $cx {
        for (0 .. $y - 1) -> $cy {
            %starts{cencode($cx, $cy)}++;
        }
    }

Store the largest block we've seen.

    my $maxblock = 0;

If there are any start points left,

    while (%starts.elems > 0) {

Pick one at random. (It doesn't matter which one it is, so if your language's hash preserves insertion order that'll work too.)

        my $start = %starts.keys[0];
        my @cstart = cdecode($start);

Set up a FIFO queue. (Yes, I can do recursion. I just don't like it when the task is more than trivial.)

        my @queue;

Also we'll have a set of points visited on this search.

        my %visited = SetHash.new;

Initialise both.

        %visited{$start}++;
        @queue.push($start);

Do a standard breadth-first search (depth-first would also work).

        while (@queue.elems > 0) {
            my $here = @queue.shift;
            my @chere = cdecode($here);

For each possible neigbour location,

            for ([-1, 0], [1, 0], [0, -1], [0, 1]) -> @delta {

make sure it lies within the grid

                if ((@delta[0] >= 0 || @chere[0] > 0)
                    && (@delta[0] <= 0 || @chere[0] < $x - 1)
                    && (@delta[1] >= 0 || @chere[1] > 0)
                    && (@delta[1] <= 0 || @chere[1] < $y - 1)) {

and calculate its coordinates.

                    my @cthere = [@chere[0] + @delta[0], @chere[1] + @delta[1]];
                    my $there = cencode(@cthere[0], @cthere[1]);

If we havent yet visited it, and it contains the same symbol as at the start point,add it to the queue and mark it as visited.

                    if (%visited{$there}:!exists &&
                        @a[@cthere[1]][@cthere[0]]
                        eq @a[@cstart[1]][@cstart[0]]) {
                        %visited{$there}++;
                        @queue.push($there);
                    }
                }
            }
        }

At this point we've visited every location that's reachable from the start. The number of locations we visited is the size of the block.

        my $size = %visited.elems;
        if ($size > $maxblock) {
            $maxblock = $size;
        }

No location we've visited needs to be a start point for future testing, because it would just give the same result. So remove them all from the starts list.

        %starts = %starts (-) %visited;
    }

And return the maximum block size found.

    return $maxblock;
}

In some languages (Rust, Python, Kotlin, Scala, Crystal, and possibly others I don't know well enough) I can use a tuple as the key and avoid the c variables and the encode/decode stepx.

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