diff options
author | ubq323 <ubq323@ubq323.website> | 2025-06-05 16:04:05 +0100 |
---|---|---|
committer | ubq323 <ubq323@ubq323.website> | 2025-06-05 16:04:05 +0100 |
commit | 2d04580e0ec8978cfcd817171086f80ceb566e7b (patch) | |
tree | 16c39197e9036d48fc6bb50dff7581c7717f9a5c | |
parent | 464255a53558e9b2466b76e37432cafe8e7894c6 (diff) |
import rle.lua from hexemu
-rw-r--r-- | rle.lua | 50 |
1 files changed, 50 insertions, 0 deletions
@@ -0,0 +1,50 @@ +-- run length encoding + +local function encode(l) + local out = {} + + local last = l[1] + local count = 1 + + local function ap() + if count == 1 then + table.insert(out,last) + elseif count == 2 then + table.insert(out,last) + table.insert(out,last) + else + table.insert(out,{count,last}) + end + end + + for ix=2,#l do + local val = l[ix] + if val == last then + count = count + 1 + else + ap() + last = val + count = 1 + end + end + + ap() + + return out +end + +local function decode(l) + local out = {} + for _,r in ipairs(l) do + if type(r) == "table" and #r == 2 then + for i = 1,r[1] do + table.insert(out,r[2]) + end + else + table.insert(out,r) + end + end + return out +end + +return {encode=encode,decode=decode} |