Sha256: fde6fb26f0c089b810a085f244bff1d1b322d9ac2806a217be1a3289d61fc878

Contents?: true

Size: 724 Bytes

Versions: 234

Compression:

Stored size: 724 Bytes

Contents

module RailsGuides
  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

234 entries across 195 versions & 21 rubygems

Version Path
railties-3.2.22.5 guides/rails_guides/levenshtein.rb
railties-3.2.22.4 guides/rails_guides/levenshtein.rb
railties-3.2.22.3 guides/rails_guides/levenshtein.rb
railties-3.2.22.2 guides/rails_guides/levenshtein.rb
railties-3.2.22.1 guides/rails_guides/levenshtein.rb
active_mailer-0.0.10 test/fixtures/dummyapp_rails_3.2/vendor/bundle/ruby/1.9.1/gems/railties-3.2.12/guides/rails_guides/levenshtein.rb
railties-3.2.22 guides/rails_guides/levenshtein.rb
judge-2.0.5 vendor/bundle/ruby/2.1.0/gems/railties-3.2.12/guides/rails_guides/levenshtein.rb
railties-3.2.21 guides/rails_guides/levenshtein.rb
railties-3.2.20 guides/rails_guides/levenshtein.rb
railties-3.2.19 guides/rails_guides/levenshtein.rb
railties-3.2.18 guides/rails_guides/levenshtein.rb
railties-3.2.17 guides/rails_guides/levenshtein.rb
railties-3.2.16 guides/rails_guides/levenshtein.rb
railties-3.2.15 guides/rails_guides/levenshtein.rb
railties-3.2.15.rc3 guides/rails_guides/levenshtein.rb
railties-3.2.15.rc2 guides/rails_guides/levenshtein.rb
railties-3.2.15.rc1 guides/rails_guides/levenshtein.rb
railties-3.2.14 guides/rails_guides/levenshtein.rb
railties-3.2.14.rc2 guides/rails_guides/levenshtein.rb