From 1c70e2dcaebe1bb18ec7d28f2caf2495efd5717d Mon Sep 17 00:00:00 2001 From: Alexander Pickering Date: Sun, 5 Jun 2016 20:58:42 -0400 Subject: Fixed a bug in hamming distance, and improved comments --- fuzzel.lua | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) (limited to 'fuzzel.lua') diff --git a/fuzzel.lua b/fuzzel.lua index f86de5c..f3432dc 100644 --- a/fuzzel.lua +++ b/fuzzel.lua @@ -1,7 +1,7 @@ --[[ Fuzzel v1.0 - Alexander "Apickx" Pickering Entered into the public domain June 2, 2016 - You are not required to, but consider linking back to the source! + You are not required to, but consider putting a link to the source in your file's comments! Some helper functions for calculateing distance between two strings @@ -97,6 +97,8 @@ fuzzel.fsd = fuzzel.FuzzySortDistance fuzzel.fsr = fuzzel.FuzzySortRatio ]] + +--Assign locals to these to the minifier can compress the file better local strlen,chrat,min,asrt,prs,iprs,typ,upack,tblins,tblsrt = string.len,string.byte,math.min,assert,pairs,ipairs,type,unpack,table.insert,table.sort local fuzzel = {} @@ -178,7 +180,7 @@ function fuzzel.HammingDistance(stringa,stringb) asrt(len == strlen(stringb),"Hamming Distance cannot be calculated on two strings of different lengths:\"" .. stringa .. "\" \"" .. stringb .. "\"") local dist = 0 for i = 1,len do - dist = dist + (chrat(stringa,i) ~= chrat(stringb,i) and 1) + dist = dist + ((chrat(stringa,i) ~= chrat(stringb,i)) and 1 or 0) end return dist end @@ -190,7 +192,10 @@ end fuzzel.hr = fuzzel.HammingRatio local function FuzzySearch(str,func,...) + --Allow varargs, or a table local looparg = typ(arg[1]) == "table" and arg[1] or arg + + --Find the string with the shortest distance to the string we were supplied local tmin = func(looparg[1],str) local sout = looparg[1] for k,v in prs(looparg) do @@ -213,18 +218,25 @@ function fuzzel.FuzzyFindRatio(str,...) end local function FuzzySort(str, func, ...) + --allow varargs, or a table local looparg = typ(arg[1]) == "table" and arg[1] or arg + + --Roughly sort everything by it's distance to the string local usorted = {} for k,v in prs(looparg) do local dist = func(str,v) usorted[dist] = usorted[dist] or {} tblins(usorted[dist],v) end + + --Actually sort them into something can can be iterated with ipairs local sorted = {} for k,v in prs(usorted) do tblins(sorted,k) end tblsrt(sorted) + + --Then build our output table local otbl = {} for k,v in prs(sorted) do for i,j in prs(usorted[v]) do -- cgit v1.2.3-70-g09d2