Advertisement
Freack100

BWT

Aug 21st, 2015
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.90 KB | None | 0 0
  1. local bwt = {}
  2.  
  3. local function rollOver(num,limit)
  4.     return num%limit
  5. end
  6.  
  7. local function rollOverString(str,startPos)
  8.     return str:sub(startPos,#str)..str:sub(1,startPos-1)
  9. end
  10.  
  11. local function copy(t)
  12.     local tt = {}
  13.     for k,v in pairs(t) do tt[k] = v end
  14.     return tt
  15. end
  16.  
  17. local function lexSort(tbl)
  18.     local function sorter(a,b)
  19.         return string.lower(a) < string.lower(b)
  20.     end
  21.     table.sort(tbl,sorter)
  22.     return tbl
  23. end
  24.  
  25. local function getRotations(str)
  26.     local limit = #str
  27.     local rot = {}
  28.     for i = 1,#str do
  29.         rot[#rot+1] = rollOverString(str,i)
  30.     end
  31.     return rot
  32. end
  33.  
  34. local function tSub(tbl,f,l)
  35.     local sub = {}
  36.     for k,v in pairs(tbl) do
  37.         sub[k] = v:sub(f,l)
  38.     end
  39.     return sub
  40. end
  41.  
  42. local function addToTable(tbl,add)
  43.     local t = {}
  44.     for k,v in pairs(add) do
  45.         t[k] = v..tbl[k]
  46.     end
  47.     return t
  48. end
  49.  
  50. local function split(str)
  51.     local tbl = {}
  52.     for c in str:gmatch(".") do
  53.         tbl[#tbl+1] = c
  54.     end
  55.     return tbl
  56. end
  57.  
  58. function bwt.searchEndCharacter(str,offset)
  59.     local os = offset and offset or 0
  60.     local possibleChars = "abcdefghijklmnopqrstuvwxyz1234567890?=)(/%\"\\}][{-.,;:_#+~<>|@*"
  61.     for i = 1,#possibleChars do
  62.         if(not string.find(str,possibleChars:sub(i,i))) then
  63.             return possibleChars:sub(i+os,i+os)
  64.         end
  65.     end
  66.     return nil
  67. end
  68.  
  69. function bwt.BWT(str,endc)
  70.     local ed = endc and endc or bwt.searchEndCharacter(str)
  71.     if(not str:find(ed)) then str = str..bwt.searchEndCharacter(str) end
  72.     local rotations = getRotations(str)
  73.     local sorted = lexSort(rotations)
  74.     local sub = tSub(sorted,#str,#str)
  75.  
  76.     return table.concat(sub,""),ed
  77. end
  78.  
  79.  
  80.  
  81. function bwt.reverseBWT(str,ed)
  82.     local splitted = split(str)
  83.     local cur = split(str)
  84.     cur = lexSort(cur)
  85.     for i = 1,#str do
  86.         cur = addToTable(cur,splitted)
  87.         cur = lexSort(cur)
  88.     end
  89.     for k,v in pairs(cur) do
  90.         if(v:sub(#v,#v) == ed) then
  91.             return v:sub(2,#v)
  92.         end
  93.     end
  94.     error("Something went wrong!")
  95. end
  96.  
  97.  
  98.  
  99. _G["bwt"] = bwt
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement