summaryrefslogtreecommitdiff
path: root/common/rle.lua
blob: 2944c4ca441d7df2d5b031c7bbc2b3a59d30f85f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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}