Ruby anagram solver

RailsSon picture RailsSon · Aug 23, 2011 · Viewed 21.8k times · Source

I am wanting to write a anagram type solver in Ruby but it will work against a list of words, like so.

List of words is:

the
these
one
owner

I would allow the user to input some letters, e.g noe, and it would search the word list for words that it can make using the letters the user has input and would bring back one and if they entered "eth" or even "the" it would bring back the. I have been trying to think of a efficient way to do this but I have been looping around each word, match a letter in the word, checking the word for each letter and both lengths match. Can anyone give advice of a better and more efficient way to do this?

Answer

Rob Neuhaus picture Rob Neuhaus · Aug 23, 2011

The big idea is that all anagrams are identical when sorted. So if you build a hash (don't know what Ruby calls these) of lists, where the keys are sorted words and the value is the list of words that sorts to the given key, then you can find anagrams very quickly by sorting the word and looking up in your hash.