# Solving a word search puzzle

In the previous post I showed a nice snippet/trick at the bottom of the post to find all the neighbors in a 2D array.

Last week I used this snippet to solve a word search puzzle a colleague created for us as a “Back to work in 2019”-challenge:

(Note: Some fellow developer colleagues think that solving the puzzle with code is unfair… heh. really?!)

Here is the complete code:

First we’ll need to read in all the possible words we’re looking for. And using the new Java streams this is very easy. Just download one of the many online word-lists and do the following:

It was never easier in Java to do File IO and manipulate collections. Next I embedded the entire puzzle and turned it into an array of Strings.

# Finding all the words

Finally we need to traverse all the possible combinations a word can be made and check against the Set of target words. I’m doing this the dumbest way possible.

First I go over each possible start location by enumerating all x/y combinations:

Next I check each direction using the neighbor algorithm from the previous post.

Now we start building the possible word, using two new pointers (tx and ty):

While we are within the bounds of the puzzle we must travel in the current ‘direction’. This is done by adding the direction offset (from previous post) to the tx and ty pointers.

If the word in-progress matches one we’re searching for, add it to the found words list!

Finally let’s close everything off, for developers with OCD like me:

This prints the words, sorted, just as we want. Q.E.D..

# Improvements

The way we now iterate over all the possible word hiding places is very very dumb.

There are some obvious improvements to be made here, for example one could place the entire lexicon in a tree-like structure instead of a set of words and stop iterating if the certain branch doesn’t exist.

However, for this puzzle, this challenge, the speed it runs at is good enough!