Sunday, March 10, 2013

LocoWordFinder Part II

LocoWordFinder, Part II

In Part I we looked at converting a dictionary text file into a format suitable for javascript. Then we created a simple client website where the user is presented anagrams of words, live, as they are typed in. Next we're going to add blanks, and make the client look a little nicer.

The final files can be found on github.

Blanks


We want to allow the user to use '?' in the search term to represent any character. If we ask for the anagrams of 'cv?' we want the program to return 'vac' (the only three letter word containing v and c).

To do this, instead of looking up just one request, we look up 26^n, where n is the number of blanks we have. We achieve this by changing the client code slightly. Instead of searching for requested string, we make a new function, function get_strings(word) which returns a list of strings for a word where any '?'s get replaced with all possible letters (if there are no '?'s, we simply return a list with just the original string).

The function looks like:
function get_strings(word)
{
 //we return a list of the strings to check, with no blanks, it's simply the sorted letters in word
 ret=[];
 var bytes=str_to_chars(word)

 var blanks=[]; //index of our blank squares
 for(var i=0; i<bytes.length; i++)
 {
  if(bytes[i]=='?')
   blanks.push(i);
 }

 if(blanks.length>0)
 {
  for(var i=0; i<Math.pow(26, blanks.length); i++)
  {
   var local_bytes=bytes.slice(0);
   var modi=i;
   for(var bi=0; bi<blanks.length; bi++)
   {
    local_bytes[blanks[bi]] = String.fromCharCode(97+modi%26); //97 =='a'
    modi /= 26;
   }
   local_bytes.sort();
   ret.push(local_bytes)
  }
 }
 else
 {
  bytes.sort()
  ret.push(bytes);
 }
 return ret;
}
We then call our recursive anagram function, recuranagram, repeatedly with each returned string.

Scoring, Sorting and Formatting

We also want to score the words, and, to make things look nicer, I decided to put the words in a table, with each column containing words with the same number of letters. Another nice feature is to indicate whether a found word has a blank in it, so there's a function to put html tags around any blanks in a word. Finally, we add a simple regex filter: if this is specified, only words that match the regex will be returned.

I've added some CSS to the top of the file to make the table look a little nicer.

The file can be found  here. It needs the anagram.js file from the previous post to work.

In the final part we'll look at making the anagram.js file a little smaller.

No comments:

Post a Comment