tstrdist.nim 555 B

123456789101112131415161718192021222324252627
  1. # compute the edit distance between two strings
  2. proc editDistance(a, b: string): int =
  3. var
  4. c: seq[int]
  5. n = a.len
  6. m = b.len
  7. newSeq(c, (n+1)*(m+1))
  8. for i in 0..n:
  9. c[i*n] = i # [i,0]
  10. for j in 0..m:
  11. c[j] = j # [0,j]
  12. for i in 1..n:
  13. for j in 1..m:
  14. var x = c[(i-1)*n + j]+1
  15. var y = c[i*n + j-1]+1
  16. var z: int
  17. if a[i-1] == b[j-1]:
  18. z = c[(i-1)*n + j-1]
  19. else:
  20. z = c[(i-1)*n + j-1]+1
  21. c[(i-1)*n + (j-1)] = min(x,min(y,z))
  22. return c[n*m]
  23. doAssert editDistance("abc", "abd") == 3