--- Day 4: W-ord search ---

December 4

Listening to: X-MAZ Medley


A word search! How fun.

Treat the word search as a 2d array; for each letter of XMAS, starting with X, search in each of eight directions to see if the word is present.

// Note: returns int instead of bool to count easier
private int IsPresent(int x, int y, int index, int xdir, int ydir)
{
    // Base condition
    if (index >= word.Length) return 1;

    // Bounds check
    if (x < 0 || x >= grid.Count || y < 0 || y >= grid[0].Count) return 0;

    if (grid[x][y] == word[index])
    {
        return IsPresent(x + xdir, y + ydir, index + 1, xdir, ydir);
    }

    return 0;
}
int count = 0;

for (int x = 0; x < grid.Count; x++)
{
    for (int y = 0; y < grid.Count; y++)
    {
        count += IsPresent(x, y, 0, -1, -1);
        count += IsPresent(x, y, 0, -1, 0);
        count += IsPresent(x, y, 0, -1, 1);
        count += IsPresent(x, y, 0, 0, -1);
        count += IsPresent(x, y, 0, 0, 1);
        count += IsPresent(x, y, 0, 1, -1);
        count += IsPresent(x, y, 0, 1, 0);
        count += IsPresent(x, y, 0, 1, 1);
    }
}

Oooooh, this part 2 is a bit of a gotcha. My solution for part 1 is basically unusable...

Actually, on thinking for a minute, it's not entirely unusuable. In fact, it's very usable!

I need to find every MAS that goes right-to-left, then check to see if MAS also exists in the matching diagonal positions. Just a little extra logic around IsPresent().

for (int x = 0; x < grid.Count; x++)
{
    for (int y = 0; y < grid.Count; y++)
    {
        if (IsPresent(x, y, 1, 1, 1) == 1 && (IsPresent(x + 2, y, 1, -1, 1) == 1 || IsPresent(x, y + 2, 1, 1, -1) == 1))
        {
            count++;
        }

        if (IsPresent(x, y, 1, -1, -1) == 1 && (IsPresent(x, y - 2, 1, -1, 1) == 1 || IsPresent(x - 2, y, 1, 1, -1) == 1))
        {
            count++;
        }
    }
}

Time taken: 40 minutes

My solutions for today's puzzles