From: "Jesús Gabriel y Galán" Date: 2007-10-21T07:20:57+09:00 Subject: Re: combinations listing On 10/20/07, Michael Linfield wrote: > Alright I'd have to say im amazed at the speed....now my question > remains how does it all work lol? > > ############# > > words = Hash.new([]) > > File.open("dict1.txt", "r") do |file| #opens the dictionary file > while line = file.gets #sets line equal to all the data in > the file Line is set to each line in the file, not to the whole file. The while loops through all the lines in the file one at a time. > word = line.chomp #knocks the \n's off the words > words[word.split('').sort!.join('')] += [word] > > #this is the one im hazy about > #it splits every letter in the file, sorts it alphabetically, joins them > all #together to form one long continuous line of letters, and combines > that to the #words pulled from the dictionary? It splits every letter of one word, sorts the letters and joins them again. Then appends to the array corresponding to the value of the sorted letters the actual word. For example, if this were the dictionary file: abc acb for abc: word.split('') --> %w{a, b, c} .sort --> %w{a, b, c} .join('') --> "abc" words["abc"] += ["abc"] --> {"abc" --> ["abc"]} now for acb: word.split('') --> %w{a, c, b} .sort --> %w{a, b, c} .join('') --> "abc" words["abc"] += ["acb"] --> {"abc" --> ["abc", "acb"]} Hope you see how the hash is built. For each set of letters it creates an array with the words that have those letters. > end > end > > File.open("word_hash", "w") do |file| #creates a new file named > word_hash > Marshal.dump(words, file) #writes the output from the words hash to > the file? Yes, serializes the hash to a file in binary form: fast to convert back to a hash. > end > > ################ > > words = nil #makes the words hash equal to nothing > > File.open("word_hash", "r") do |file| #loads the data > words = Marshal.load(file) > end Here's where the serliazed hash is brought back to life. > > while true > print "Enter word: " > anagram = gets.chomp > sorted_anagram = anagram.split('').sort!.join('') #sorts it the same > way as #the words hash? Yes, to obtain the key to the hash --> "abc" > > p words[sorted_anagram] > end Hope this helps, Jesus.