+ string_init (&string);
+
+ trie_print (dict->trie, &string);
+
+ string_fini (&string);
+}
+
+char *cube_faces[16] = {
+ "aaeeng", "abbjoo", "achops", "affkps",
+ "aoottw", "cimotu", "deilrx", "delrvy",
+ "distty", "eeghnw", "eeinsu", "ehrtvw",
+ "eiosst", "elrtty", "himnqu", "hlnnrz"
+};
+
+typedef struct _board {
+ char letters[4][4];
+
+ /* Private, transient state used by enumerate */
+ trie_t *result_trie;
+} board_t;
+
+int
+rand_within (int num_values)
+{
+ return (int) ((double) num_values * (rand() / (RAND_MAX + 1.0)));
+}
+
+void
+shuffle (int *array, int length)
+{
+ int i, r, tmp;
+
+ for (i = 0; i < length; i++)
+ {
+ r = i + rand_within (length - i);
+ tmp = array[i];
+ array[i] = array[r];
+ array[r] = tmp;
+ }
+}
+
+void
+board_init (board_t *board)
+{
+ int i;
+ int cubes[16];
+
+ for (i = 0; i < 16; i++)
+ cubes[i] = i;
+ shuffle (cubes, 16);
+
+ for (i = 0; i < 16; i++)
+ board->letters[i / 4][i % 4] = cube_faces[cubes[i]][rand_within(6)];
+}
+
+void
+board_print (board_t *board)
+{
+ int x, y;
+ char c;
+
+ for (y = 0; y < 4; y++) {
+ for (x = 0; x < 4; x++) {
+ c = board->letters[y][x];
+ printf (" %c%s", toupper (c),
+ c == 'q' ? "u" : " ");
+ }
+ printf ("\n");
+ }
+}
+
+#define SEEN_BIT(x, y) (1 << (4*(y)+(x)))
+void
+board_enumerate (board_t *board,
+ int x,
+ int y,
+ int16_t seen,
+ string_t *word,
+ trie_t *dict_trie)
+{
+ char c;
+ int dx, dy;
+
+ if (x < 0 || x >= 4 ||
+ y < 0 || y >= 4 ||
+ seen & SEEN_BIT (x, y))
+ {
+ return;
+ }
+
+ seen |= SEEN_BIT (x, y);
+
+ c = board->letters[y][x];
+ string_append_char (word, c);
+ dict_trie = dict_trie->next[TRIE_CHAR_TO_INDEX (c)];
+ if (dict_trie == NULL)
+ goto BAIL0;
+
+ if (c == 'q') {
+ string_append_char (word, 'u');
+ dict_trie = dict_trie->next[TRIE_CHAR_TO_INDEX ('u')];
+ if (dict_trie == NULL)
+ goto BAIL1;
+ }
+
+ if (dict_trie->is_word)
+ trie_add (board->result_trie, word->s);
+
+ for (dy = -1; dy <= 1; dy++)
+ for (dx = -1; dx <= 1; dx++)
+ board_enumerate (board, x + dx, y + dy, seen, word, dict_trie);
+
+ BAIL1:
+ if (c == 'q')
+ string_chop (word);
+ BAIL0:
+ string_chop (word);
+}
+
+void
+board_solve (board_t *board, dict_t *dict)
+{
+ int x, y;
+ int16_t seen = 0;
+ string_t word;
+
+ board->result_trie = trie_create ();
+
+ string_init (&word);
+
+ for (y = 0; y < 4; y++)
+ for (x = 0; x < 4; x++)
+ board_enumerate (board, x, y, seen, &word, dict->trie);
+ printf ("\n");
+
+ string_fini (&word);
+
+ string_init (&word);
+ trie_print (board->result_trie, &word);
+ printf ("\n");
+ string_fini (&word);
+
+ trie_destroy (board->result_trie);