RogerBW's Blog

The Weekly Challenge 220: Square Commoners 11 June 2023

I’ve been doing the Weekly Challenges. The latest involved word breakdowns and perfect squares. (Note that this is open until 11 June 2023.)

Task 1: Common Characters

You are given a list of words.

Write a script to return the list of common characters (sorted alphabeticall) found in every word of the given list.

Some languages have sets with full function support. Some don't.

I took word2set from challenge 216 task #1. Python:

def word2set(word):
  r = set()
  for c in word.lower():
    if c >= 'a' and c <= 'z':
  return r

def commoncharacters(lst):
  c = word2set(lst[0])
  for w in lst[1:]:
    c = c.intersection(word2set(w))
  return sorted(list(c))

Probably this could be done with a reduce or equivalent, but that's not really part of my standard mental programming toolbox.

For languages like Perl, the set intersection is more a matter of looking through the keys of c and deleting any that don't appear in the set from the other word.

Task 2: Squareful

You are given an array of integers, @ints.

An array is squareful if the sum of every pair of adjacent elements is a perfect square.

Write a script to find all the permutations of the given array that are squareful.

For languages without permutation readily available, I borrowed code from challenge 154 task #1.

More interesting is the way that in some languages an array is a perfectly good set key and a thing that can be sorted; in others, rather less so. In some cases I changed the sequence into a base-X number (X being one higher than the highest value) for easier manipulation, then broke it down again for output.

I decided to make things a bit more interesting by having a squareness-tester that automatically extended itself as needed.

A shorthand function for squaring things:

sub squared($a) {
  return $a * $a;

Sequence decoder (base-X number to sequence):

sub decode($a0, $base) {
  my @eq;
  my $a = $a0;
  while ($a > 0) {
    unshift @eq, $a % $base;
    $a = int($a / $base);
  return \@eq;

Sequence encoder (sequence to base-X number):

sub encode($sq, $base) {
  my $a = 0;
  foreach my $v (@{$sq}) {
    $a *= $base;
    $a += $v;
  return $a;

The main function. Set up hashest (sets) to catch results, and for the self-extending squares list.

sub squareful($lst) {
  my %results;
  my %squares;

Determine the base for sequence encdding.

  my $base = max(@{$lst}) + 1;

For each possible permutation of input digits:

  my $p = Algorithm::Permute->new($lst);
  while (my @la = $p->next) {

Only one adjacent combination need not be squareful to disqualify this permutation.

    my $squareful = 1;

Go through the permutation by overlapping digit pairs.

    foreach my $i (0 .. $#la - 1) {
      my $cs = $la[$i] + $la[$i + 1];

What's the highest perfect square we already know about? (Taking the length of the hash and squaring it should be faster than retrieving its maximum value.)

      my $mx = squared(scalar keys %squares);

If the value under test is higher, extend the squares hash until it isn't.

      while ($cs > $mx) {
        $mx = squared((scalar keys %squares) + 1);
        $squares{$mx} = 1;

If it's not a perfect square, bail out on this permutation.

      unless (exists $squares{$cs}) {
        $squareful = 0;

If this was a squareful permutation, code it up. (If the permutor produces duplicates, this will get rid of them.)

    if ($squareful) {
      $results{encode(\@la, $base)} = 1;

Now take those results, sort them, decode them, and stick them in the output list.

  return [map {decode($_, $base)} sort {$a <=> $b} keys %results];

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.

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