0

I found this ruby method on a wiki that finds the number of differences between two strings.

def levenshtein(first, second)
  matrix = [(0..first.length).to_a]
  (1..second.length).each do |j|
    matrix << [j] + [0] * (first.length)
  end

  (1..second.length).each do |i|
    (1..first.length).each do |j|
      if first[j-1] == second[i-1]
        matrix[i][j] = matrix[i-1][j-1]
      else
        matrix[i][j] = [
          matrix[i-1][j],
          matrix[i][j-1],
          matrix[i-1][j-1],
        ].min + 1
      end
    end
  end
  return matrix.last.last
end

How can I edit it so that it also returns the physical differences between the two strings, meaning that if I were to enter "test test test test" and "test tebt test test" it would return "test te/b/t test test" with slashes around the difference so that i can display it differently. (I still want the number as well.)

shirakia
  • 2,369
  • 1
  • 22
  • 33
  • What you want to obtain is quite different from the levenshtein purposes; you should start from scratch – mdesantis Dec 16 '14 at 22:24
  • What would be the best way to go about doing that? – Peter Sauer Dec 16 '14 at 22:38
  • You'll have to define exactly how you want to display the differences. Differences can be substituted, missing, or inserted. How do you intend to display these differences ? – roob Dec 16 '14 at 23:05
  • This is a helpful introduction to string comparison and proximity: http://alias-i.com/lingpipe/demos/tutorial/stringCompare/read-me.html – joelparkerhenderson Dec 17 '14 at 00:21
  • a tool like [diff-lcs](https://github.com/halostatue/diff-lcs) would probably be more appropriate to this task. – m_x Dec 17 '14 at 10:26

0 Answers0