Permalink
Browse files

speed up levenshtein distance

This speeds up levenshtein distance calculation by about 1.6x
  • Loading branch information...
1 parent 1b92cc6 commit a7b2c2d24349ab76fd7ee7bd51568bc6a99eecd4 @tenderlove tenderlove committed Feb 5, 2014
Showing with 12 additions and 2 deletions.
  1. +12 −2 lib/rubygems/text.rb
View
@@ -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 a7b2c2d

Please sign in to comment.