darraghd493

Levenshtein distance - Lua implementation

Oct 23rd, 2023 (edited)
833
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.96 KB | Source Code | 0 0
  1. --[[
  2.     Levenshtein distance implemented in lua
  3.     Made by darraghd493
  4. ]]
  5.  
  6. local module = {}
  7.  
  8. module.distance = function(s1, s2)
  9.     s1 = string.lower(s1)
  10.     s2 = string.lower(s2)
  11.  
  12.     local costs = {}
  13.  
  14.     for i=1,#s1 do
  15.         local last = i;
  16.         for j=1,#2 do
  17.             if i == 1 then
  18.                 costs[j] = j
  19.             elseif j > 1 then
  20.                 local newValue = costs[j-1]
  21.                 if s1:sub(i,i) ~= s2:sub(j,j) then
  22.                     newValue = math.min(math.min(newValue, last), costs[j]) + 1
  23.                 end
  24.                 costs[j-1] = last
  25.                 last = newValue
  26.             end
  27.         end
  28.     end
  29.  
  30.     return costs[#costs]
  31. end
  32.  
  33. module.similarity = function(s1, s2)
  34.     local longer = if #s1 > #s2 then s1 else s2
  35.     local shorter = if #s1 < #s2 then s1 else s2
  36.  
  37.     if #longer == 0 then return 1 end
  38.  
  39.     return (#longer - module.distance(longer, shorter)) / #longer
  40. end
  41.  
  42. return module
Advertisement
Add Comment
Please, Sign In to add comment