Advertisement
Doob

lz77

May 31st, 2016
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.01 KB | None | 0 0
  1. local function e_char(str1, str2)
  2.   local l
  3.   if #str1 < #str2 then
  4.     l = #str1
  5.   else
  6.     l = #str2
  7.   end
  8.   local i = 1
  9.   while i <= l and str1:sub(i, i) == str2:sub(i, i) do
  10.     i = i + 1
  11.   end
  12.   if i <= l then
  13.     return i - 1
  14.   else
  15.     return l
  16.   end
  17. end
  18.  
  19. local function lz77(text, sw_l)
  20.   sw_l = sw_l or 6
  21.   local o = 1
  22.   local eof = false
  23.   while not eof do
  24.     local sw_o = o - sw_l
  25.     if sw_o < 1 then sw_o = 1 end
  26.     local sw = text:sub(sw_o, o - 1)
  27.     local o_text = text:sub(o)
  28.     local lg = 0
  29.     local lg_pos = 0
  30.     for i = 1, #sw do
  31.       local n = e_char(sw:sub(i), o_text)
  32.       if n > lg then
  33.         lg = n
  34.         lg_pos = i
  35.       end
  36.     end
  37.     local f_pos = o + lg
  38.     local f
  39.     if f_pos <= #text then
  40.       f = text:sub(f_pos, f_pos)
  41.     else
  42.       f = "]"
  43.       eof = true
  44.     end
  45.     io.write(string.char(lg_pos)..string.char(lg)..f)
  46.     --print(string.format("(%d, %d, %s)", lg_pos, lg, f))
  47.     o = f_pos + 1
  48.   end
  49. end
  50.  
  51. lz77("blablablabla", 30)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement