RogerBW's Blog

The Weekly Challenge 335: The Commoners are Winning Characters 24 August 2025

I’ve been doing the Weekly Challenges. The latest involved character sieving and noughts and crosses. (Note that this ends today.)

Task 1: Common Characters

You are given an array of words.

Write a script to return all characters that is in every word in the given array including duplicates.

A fairly straightforward flow of logic. In JavaScript:

function commoncharacters(a) {

Set up the counter.

    let mc = new Map;
    let first = true;

Look at each string.

    for (let s of a) {

Turn it into a counted hash (utility function not included here, but it's in the full source).

        const mk = counterify(s.split(""));

First time through, make the working counter a copy of this one.

        if (first) {
            mc = mk;
            first = false;
        } else {

Otherwise, look through each key and take the minimum, reducing or deleting entries as found.

            for (let k of mc.keys()) {
                if (mk.has(k)) {
                    mc.set(k, Math.min(mc.get(k), mk.get(k)));
                } else {
                    mc.delete(k);
                }
            }
        }
    }

Now to assemble the output.

    let out = [];

Sort the keys into order.

    let kl = [...mc.keys()];
    kl.sort();

For each key…

    for (let c of kl) {

The relevant number of times…

        for (let n = 1; n <= mc.get(c); n++) {

Append the key value.

            out.push(c);
        }
    }
    return out;
}

In Rust, using the counter class lets me do intersections as a single operation, so the chunk under "Otherwise, look through each key" can be trivially replaced:

            mc = mc & mk;

Maybe that doesn't save a lot of code, but I like to shift that stuff onto someone else's code.

Task 2: Find Winner

You are given an array of all moves by the two players.

Write a script to find the winner of the TicTacToe game if found based on the moves provided in the given array.

My approach is to build the board state, then check exhaustively for a winner.

Perl:

sub findwinner($a) {

Set up the empty board.

  my @board = (
    [ 0, 0, 0 ],
    [ 0, 0, 0 ],
    [ 0, 0, 0 ],
      );

We will call the first player "1".

  my $player = 1;

Iterate through the plays provided, mapping them into the board.

  foreach my $play (@{$a}) {
    $board[$play->[0]][$play->[1]] = $player;
    $player = 3 - $player;
  }

Check for possible winning rows. Each line is X base, Y base, X offset, Y offset; so the first line will generate (0, 0), (1, 0) and (2, 0).

  foreach my $pattern (
    [0, 0, 1, 0],
    [0, 1, 1, 0],
    [0, 2, 1, 0],
    [0, 0, 0, 1],
    [1, 0, 0, 1],
    [2, 0, 0, 1],
    [0, 0, 1, 1],
    [0, 2, 1, -1],
      ) {

Initialise a set (a hash in Perl which doesn't have sets) to hold the values found in a given line.

    my %cellvals;

Look at the three positions along the line, and store the contents in the set.

    foreach my $i (0 .. 2) {
      my $x = $pattern->[0] + $i * $pattern->[2];
      my $y = $pattern->[1] + $i * $pattern->[3];
      $cellvals{$board[$y][$x]}++;
    }

If there is only one distinct value (i.e. all three cells had the same value):

    if (scalar keys %cellvals == 1) {

Pull out that value.

      my $winner = (keys %cellvals)[0];

If it's a valid player, return that player as the winner.

      if ($winner == 1) {
        return "A";
      } elsif ($winner == 2) {
        return "B";
      }
    }
  }

If we get to the end, we have no winner. If the board is full, call it a draw, otherwise call it pending.

  if (scalar @{$a} == 9) {
    return "Draw";
  } else {
    return "Pending";
  }
}

This algorithm does not attempt to distinguish between incomplete and winnable games as in example 4,

X | . | .
--+---+--
. | O | .
--+---+--
. | . | .

and incomplete but unwinnable games (e.g., with X to play):

O | X | X
--+---+--
X | X | O
--+---+--
O | O | .

Either type is returned as "Pending". The game is after all fairly trivial, and with players of more than elementary competence every game will be a draw anyway.

Full code on github.

Add A Comment

Your Name
Your Email
Your Comment

Note that I will only approve comments that relate to the blog post itself, not ones that relate only to previous comments. This is to ensure that the blog remains outside the scope of the UK's Online Safety Act (2023).

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 disaster 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 horrorm science fiction hugo 2014 hugo 2015 hugo 2016 hugo 2017 hugo 2018 hugo 2019 hugo 2020 hugo 2021 hugo 2022 hugo 2023 hugo 2024 hugo 2025 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 openscad opera parody paul temple perl perl weekly challenge photography podcast poetry politics postscript powers prediction privacy project woolsack pyracantha python quantum rail raku ranting raspberry pi reading reading boardgames social real life restaurant review 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 typst 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