Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. -- vim: set filetype=terra tabstop=3 noexpandtab :miv --
  2.  
  3. local terra min3(a : int, b : int, c : int)
  4. if a < b and a < c then
  5. return a
  6. elseif b < c then
  7. return b
  8. else
  9. return c
  10. end
  11. end
  12.  
  13. local function levenshtein_n(length)
  14. length = length + 1
  15. return terra(a : rawstring, b : rawstring)
  16. var _c : int8[length]; var c = &_c[0] -- Current
  17. var _p : int8[length]; var p = &_p[0] -- Previous
  18.  
  19. for j=0, length do
  20. c[j] = (int8)(j) -- Distance of a to empty string
  21. end
  22.  
  23. var i = 0
  24. while true do
  25. p,c = c,p
  26.  
  27. if b[i]==0 then
  28. return p[length-1]
  29. end
  30.  
  31. c[0] = i+1 -- Distance of b to empty string
  32.  
  33. for j=1,length do
  34. var deletioncost : int = p[j]+1
  35. var insertioncost : int = c[j-1]+1
  36. var substitutioncost : int = p[j-1]
  37. if a[j-1] ~= b[i] then
  38. substitutioncost = substitutioncost + 1
  39. end
  40. c[j] = min3(deletioncost, insertioncost, substitutioncost)
  41. end
  42.  
  43. i = i + 1
  44. end
  45. end
  46. end
  47.  
  48. local levenshtein = setmetatable({}, {__index=function(self, key)
  49. if type(key)=='number' then
  50. key = math.floor(key)
  51. rawset(self, key, levenshtein_n(key))
  52. return rawget(self, key)
  53. elseif type(key)=='string' then
  54. local l = #key
  55. return function(other)
  56. return self[l](key, other)
  57. end
  58. end
  59. end})
  60.  
  61. print(levenshtein.kitten "sitting")
  62. print(levenshtein.Saturday "Sunday")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement