爲見here算法來檢查單詞之間的相似性。
從那裏使用代碼,您可以使用array.any?{|e| e.similar?(user_input)}
可以根據實際需要可以調整閾值。 當然,這是紅寶石,所以你必須翻譯成JavaScript ...
我複製從那裏代碼:
class String
def levenstein(other, ins=2, del=1, sub=1)
return nil if self.nil? || other.nil?
dm = []
dm[0] = (0..self.length).collect { |i| i * ins}
fill = [0] * (self.length - 1)
for i in 1..other.length
dm[i] = [i * del, fill.flatten]
end
for i in 1..other.length
for j in 1..self.length
dm[i][j] = [
dm[i-1][j-1] + (self[i-1] == other[i-1] ? 0 : sub),
dm[i][j-1] + ins,
dm[i-1][j] + del
].min
end
end
dm[other.length][self.length]
end
def similar?(other, thresh = 2)
self.levenstein(other) < thresh
end
end
# Tryout
"Foobar".similar?("Fuubar", 3) # => true
看看這裏的Levenshtein距離:HTTP:// en.wikipedia.org/wiki/Levenshtein_distance 以及此處的實現:http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance 它爲您提供了單詞相似性的度量標準。 – peshkira 2012-07-07 17:21:14
@peshkira這將是一個很好的答案 – Stefan 2012-07-07 21:19:41