我最近一直在玩 Ruby,我刚刚完成了来自http://codekata.pragprog.com的 Anagrams Code Kata 。
该解决方案是测试驱动的,并利用了独特的素因数分解定理,但它似乎运行得非常慢。到目前为止,仅在 45k 文件上它已经运行了大约 10 分钟。任何人都可以给我任何关于提高我的代码性能的建议吗?
class AnagramFinder
def initialize
@words = self.LoadWordsFromFile("dict45k.txt")
end
def OutputAnagrams
hash = self.CalculatePrimeValueHash
@words.each_index{|i|
word = @words[i]
wordvalue = hash[i]
matches = hash.select{|key,value| value == wordvalue}
if(matches.length > 1)
puts("--------------")
matches.each{|key,value|
puts(@words[key])
}
end
}
end
def CalculatePrimeValueHash
hash = Hash.new
@words.each_index{|i|
word = @words[i]
value = self.CalculatePrimeWordValue(word)
hash[i] = value
}
hash
end
def CalculatePrimeWordValue(word)
total = 1
hash = self.GetPrimeAlphabetHash
word.downcase.each_char {|c|
value = hash[c]
total = total * value
}
total
end
def LoadWordsFromFile(filename)
contentsArray = []
f = File.open(filename)
f.each_line {|line|
line = line.gsub(/[^a-z]/i, '')
contentsArray.push line
}
contentsArray
end
def GetPrimeAlphabetHash
hash = { "a" => 2, "b" => 3, "c" => 5, "d" => 7, "e" => 11, "f" => 13, "g" =>17, "h" =>19, "i" => 23, "j" => 29, "k" => 31, "l" => 37, "m" => 41, "n" =>43, "o" =>47, "p" => 53, "q" =>59, "r" => 61, "s" => 67, "t" => 71, "u" => 73, "v" => 79, "w" => 83, "x" => 89, "y" => 97, "z" => 101 }
end
end