40 lines
1 KiB
Text
40 lines
1 KiB
Text
fun compress = List by text uncompressed
|
|
Map dictionary = text%int[].with(256, <int i|text%int(chr(i) => i))
|
|
text w
|
|
List result = int[]
|
|
for each text c in uncompressed
|
|
text wc = w + c
|
|
if dictionary.has(wc)
|
|
w = wc
|
|
else
|
|
result.append(dictionary[w])
|
|
dictionary.insert(wc, dictionary.length)
|
|
w = c
|
|
end
|
|
end
|
|
if not w.isEmpty() do result.append(dictionary[w]) end
|
|
return result
|
|
end
|
|
fun decompress = text by List compressed
|
|
Map dictionary = int%text[].with(256, <int i|int%text(i => chr(i)))
|
|
text w = chr(compressed[0])
|
|
text result = *w
|
|
for each int k in compressed.extract(1)
|
|
text entry
|
|
if dictionary.has(k)
|
|
entry = dictionary[k]
|
|
else if k == dictionary.length
|
|
entry = w + w[0]
|
|
else
|
|
error(65, "Error decompressing")
|
|
end
|
|
result.append(entry)
|
|
dictionary.insert(dictionary.length, w + entry[0])
|
|
w = entry
|
|
end
|
|
return result
|
|
end
|
|
List compressed = compress("TOBEORNOTTOBEORTOBEORNOT")
|
|
writeLine(compressed)
|
|
text decompressed = decompress(compressed)
|
|
writeLine(decompressed)
|