Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby anagram solver [closed]

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?

like image 624
RailsSon Avatar asked Aug 23 '11 21:08

RailsSon


People also ask

How do I check an anagram in Ruby?

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.

What is an anagram Ruby?

An anagram is a type of word play, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once — Wikipedia. For example: 'heart' and 'earth' are anagrams, because if you rearrange the string, you'll have the same word for both strings.


2 Answers

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.

like image 197
Rob Neuhaus Avatar answered Oct 25 '22 12:10

Rob Neuhaus


rrenaud's answer is great, and here is an example of how to construct such a hash in ruby, given an array named "words" that contains all of the words in your dictionary:

@words_hash = words.each_with_object(Hash.new []) do |word, hash|
  hash[word.chars.sort] += [word]
end

The code above assumes ruby 1.9.2. If you are using an older version then chars won't exist but you can use .split('').sort.

The default object of the hash is set to be the empty array, which makes the coding easier in some cases because you don't have to worry about the hash giving you nil.

Source: https://github.com/DavidEGrayson/anagram/blob/master/david.rb

like image 32
David Grayson Avatar answered Oct 25 '22 13:10

David Grayson