I wrote a function which makes words of the same characters (but not the same sequence) into a hash[key]
, the key is a character-sorted string of these words for example, hash_list["arst"] => ["rats""tars""star"]
.
However, line 8 in my code perhaps does something wrong and when I puts word_list
, I get a {}
.
The ".txt" file consists of many lines of words like:
alean
allow
away
be
behavior
...
...
My code:
01 def findAnagrams()
02 word_list = Hash.new([]) # I set the default value here
03 # word_list.default = Array.new
04 File.open("/home/luchen/class/words.txt").each_line do |line|
05 word = line.chomp.strip.downcase
06 word_sort = word.chars.sort.join
07 # puts word+"------"+word_sort
08 word_list[word_sort].push(word)
09 # puts word_list[word_sort]
10 end
11 puts word_list.to_s
12 end
13
14 findAnagrams()