Browse files

Merge pull request #809 from tenderlove/faster_levenshtein

Speed up levenshtein distance
  • Loading branch information...
2 parents fa57642 + a7b2c2d commit 796ce1bf23f4c02f62822acf1812ce86870adaa8 @drbrain drbrain committed Feb 5, 2014
Showing with 12 additions and 2 deletions.
  1. +12 −2 lib/rubygems/text.rb
View
14 lib/rubygems/text.rb
@@ -26,6 +26,16 @@ def format_text(text, wrap, indent=0)
result.join("\n").gsub(/^/, " " * indent)
end
+ def min3 a, b, c # :nodoc:
+ if a < b && a < c
+ a
+ elsif b < a && b < c
+ b
+ else
+ c
+ end
+ end
+
# This code is based directly on the Text gem implementation
# Returns a value representing the "cost" of transforming str1 into str2
def levenshtein_distance str1, str2
@@ -47,11 +57,11 @@ def levenshtein_distance str1, str2
m.times do |j|
cost = (s[i] == t[j]) ? 0 : 1
- x = [
+ x = min3(
d[j+1] + 1, # insertion
e + 1, # deletion
d[j] + cost # substitution
- ].min
+ )
d[j] = e
e = x
end

0 comments on commit 796ce1b

Please sign in to comment.