Sha256: 4d1e6da4797210747c7a42cf97bd4deedb3545d6cfe9cb42762754e8746399f3

Contents?: true

Size: 719 Bytes

Versions: 15

Compression:

Stored size: 719 Bytes

Contents

module Guides
  module Levenshtein
    # Based on the pseudocode in http://en.wikipedia.org/wiki/Levenshtein_distance.
    def self.distance(s1, s2)
      s = s1.unpack('U*')
      t = s2.unpack('U*')
      m = s.length
      n = t.length

      # matrix initialization
      d = []
      0.upto(m) { |i| d << [i] }
      0.upto(n) { |j| d[0][j] = j }

      # distance computation
      1.upto(m) do |i|
        1.upto(n) do |j|
          cost = s[i] == t[j] ? 0 : 1
          d[i][j] = [
            d[i-1][j] + 1,      # deletion
            d[i][j-1] + 1,      # insertion
            d[i-1][j-1] + cost, # substitution
          ].min
        end
      end

      # all done
      return d[m][n]
    end
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
guides-0.7.2 lib/guides/levenshtein.rb
guides-0.7.1 lib/guides/levenshtein.rb
guides-0.7.0 lib/guides/levenshtein.rb
guides-0.6.10 lib/guides/levenshtein.rb
guides-0.6.9 lib/guides/levenshtein.rb
guides-0.6.8.1 lib/guides/levenshtein.rb
guides-0.6.8 lib/guides/levenshtein.rb
guides-0.6.7 lib/guides/levenshtein.rb
guides-0.6.6 lib/guides/levenshtein.rb
guides-0.6.5 lib/guides/levenshtein.rb
guides-0.6.4 lib/guides/levenshtein.rb
guides-0.6.3 lib/guides/levenshtein.rb
guides-0.6.2 lib/guides/levenshtein.rb
guides-0.6.1 lib/guides/levenshtein.rb
guides-0.5.0 lib/guides/levenshtein.rb