3

I have an array that contains a few thousand words. I have an input field on my webpage that allows a user to enter in a couple of letters, and then hit search. When the user hits search, the application should look in the dictionary and see what words can be formed off of the supplied letters. Each letter can be used only once ( like in scrabble ).

Is there already a search library for doing something like this? I don't want to reinvent the wheel if not necessary. If not, does anyone have ideas for a high performance solution. I'd imagine this has been done millions of times before.

juicejonjon
  • 31
  • 1
  • 2

3 Answers3

1

John Resig of jQuery fame has been thinking about this problem as well:

http://ejohn.org/blog/dictionary-lookups-in-javascript/

duffymo
  • 305,152
  • 44
  • 369
  • 561
1

What you need to do is convert the array of words in a hashtable where the key is each word's letters sorted. Ex:

['car', 'shoe', 'train']
=> {'acr': ['car'],
     'ehos': ['shoe'],
     'ainrt': ['train']}

Then you take the user's letters, you sort them, and you do a hashtable (any dictionary impl would do, but hashtables are most efficient in this case) lookup using the sorted letters as key. The list corresponding to your key is the list of words you can do with those letters. This has the advantage of having a time complexity of O(n) = 1.

Ioan Alexandru Cucu
  • 11,981
  • 6
  • 37
  • 39
  • I really like the idea of this method, but do you have any tips for when you also allow a sub-set of the provided letters to be used? E.g. the letters 'c', 'a', 'r' and 's' could spell 'car' and 'cars'. – Michiel Jul 17 '12 at 16:48
  • 1
    Then, you would probably need tries: http://en.wikipedia.org/wiki/Trie , though I'm not sure if this is implemented in any js libary – Ioan Alexandru Cucu May 21 '13 at 01:04
1

Steve Hanov wrote something about this too:

http://stevehanov.ca/blog/index.php?id=120