r/dailyprogrammer • • Jul 16 '12

[7/16/2012] Challenge #77 [difficult] (Boggle solver)

Write a program that is able to find all words in a Boggle board. For a word list, you can use this file.

How many words can you find in the following 10x10 Boggle board?

T N L E P I A C N M
T R E H O C F E I W
S C E R E D A M E A
A O M O G O O F I E
G A C M H N L E R X
T D E R J T F O A S
I T A R T I N H N T
R N L Y I V S C R T
A X E P S S H A C F
I U I I I A I W T T

  • Thanks to Medicalizawhat for suggesting this problem (and to Cosmologicon for providing a word list and some commentary) at /r/dailyprogrammer_ideas! If you have a problem that you think would be good for us, why not head over there and suggest it?
13 Upvotes

30 comments sorted by

View all comments

Show parent comment

2

u/leonardo_m Jul 19 '12

Currently in D array literals cause a heap allocation, it's a missed optimization. Even assigning a fixed size array with a literal causes a heap allocation (take a look at the asm from your code).

In D iterating a typetuple causes the foreach to become a "static foreach", so it gets unrolled (again take a look at the asm).

1

u/leonardo_m Jul 22 '12

A little faster, this doesn't implement an Directed Acyclic Word Graph (DAWG), it just shares the leaves, using less memory. About 0.18 seconds to build the almost-trie, and about 1.5 seconds for the 100x100 search.

import std.stdio, std.algorithm, std.file, std.conv,
       std.datetime, std.string, std.typetuple, std.array;

enum bool USE_BIG_TABLE = true;
enum int FIRST = 'a';

struct Arena(T, int MAX_BLOCK_BYTES=1 << 15) {
    static struct Block {
        T[(MAX_BLOCK_BYTES / T.sizeof)] items;
    }

    static T* alloc() nothrow {
        __gshared static Block*[] blocks;
        __gshared static T* nextFree, lastFree;
        if (nextFree >= lastFree) {
            blocks ~= new Block;
            nextFree = blocks[$ - 1].items.ptr;
            lastFree = nextFree + Block.items.length;
        }
        return nextFree++;
    }
}

struct Node {
    Node*[26] letters; // a-z in alphabet, not ASCII numbered order
    bool terminal; // A complete word finishes in this Node
}

__gshared static Arena!Node nodes;

void branchNode(Node* current, in string word,
                ref Node[Node.letters.length] leaves) nothrow
in {
    assert(current);
} body {
    if (word.empty)
        return;

    immutable size_t index = word[0] - FIRST;

    if (word.length == 1) {
        // Then use a preallocated leaf
        current.letters[index] = &leaves[index];
        return;
    }

    immutable bool usedLeaf = current.letters[index] == &leaves[index];
    if (current.letters[index] == null || usedLeaf)
        current.letters[index] = nodes.alloc(); // If no Node or we are using
                                                // a preallocated leaf, then add
                                                // one node or replace
                                                // the leaf with a new node
    if (usedLeaf)
        current.letters[index].terminal = true;

    branchNode(current.letters[index], word[1 .. $], leaves);
}


string[] trieSearch(in char[][] bog, in uint y, in uint x, string s,
                    bool[][] block, in Node* current) pure nothrow {
    block[y][x] = true; // Block against retracing steps
    s ~= bog[y][x]; // Add square's letter to current string
    auto words = current.terminal ? [s] : []; // Complete word?

    // Test the 8 adjacent squares for the continuation of the word
    static struct P { uint y, x; }
    alias TypeTuple!(P(+1,  0), P(-1,  0), P( 0, +1),
                     P(+1, +1), P(-1, +1),
                     P( 0, -1), P(-1, -1), P(+1, -1)) shifts;

    foreach (syx; shifts) {
        immutable uint py = y + syx.y;
        immutable uint px = x + syx.x;
        if (py < bog.length && px < bog[py].length) // In bounds
            if (!block[py][px] && current.letters[bog[py][px] - FIRST] != null)
                words ~= trieSearch(bog, py, px, s, block,
                                    current.letters[bog[py][px] - FIRST]);
    }

    block[y][x] = false;
    return words;
}

void searchWord(in Node* root, in string w) {
    if (root == null) {
        writeln("empty root ", w);
        return;
    }

    writeln(w);

    if (!w.empty)
        searchWord(root.letters[w[0] - FIRST], w[1 .. $]);
}

void main() {
    StopWatch sw, search;
    sw.start();

    Node trieRoot;
    Node[Node.letters.length] leaves;
    foreach (ref leaf; leaves)
        leaf.terminal = true;

    foreach (word; readText("enable1.txt").split()) // Create trie structure
        branchNode(&trieRoot, word, leaves);

    const letters = "T N L E P I A C N M
                     T R E H O C F E I W
                     S C E R E D A M E A
                     A O M O G O O F I E
                     G A C M H N L E R X
                     T D E R J T F O A S
                     I T A R T I N H N T
                     R N L Y I V S C R T
                     A X E P S S H A C F
                     I U I I I A I W T T".toLower().split();

    char[][] bog;
    foreach (i; 0 .. 10) {
        bog.length++;
        foreach (j; i * 10 .. i * 10 + 10)
            bog[$ - 1] ~= letters[j];
    }

    static if (USE_BIG_TABLE) {
        writeln("Using big 100x100 table.");

        // 100x100 version
        foreach (ref line; bog) {
            char[] temp;
            foreach (i; 0 .. 10)
                temp ~= line;
            line = temp;
        }

        auto temp = bog;
        foreach (i; 0 .. 9)
            bog ~= temp;
    }

    string[] words;
    bool[][] block;
    foreach (line; bog)
        block ~= new bool[line.length];

    writeln(sw.peek().msecs, " msecs setup time");
    search.start();

    foreach (i, line; bog)
        foreach (j, letter; line)
            if (trieRoot.letters[bog[i][j] - FIRST] != null)
                words ~= trieSearch(bog, i, j, "", block,
                                    trieRoot.letters[bog[i][j] - FIRST]);

    auto maxWords = [""];
    foreach (word; words)
        if (word.length > maxWords[0].length)
            maxWords = [word];
        else if (word.length == maxWords[0].length)
            maxWords ~= word;

    writeln(search.peek().msecs, " msecs search time", );
    writeln(sw.peek().msecs, " msecs total time");

    maxWords.sort().uniq().writeln();
    maxWords[0].length.writeln();
}