LZW compression: Difference between revisions
Content deleted Content added
Added Wren |
Updated to work with Nim 1.4: removed test to "nil". Several other minor changes. |
||
Line 3,540:
=={{header|Nim}}==
<lang>import tables
proc compress*(uncompressed: string): seq[int] =
## build the dictionary▼
var dictionary = initTable[string, int]()▼
for i in 0..255:▼
var
▲ for i in 0..255: dictionary[$chr(i)] = i
var w = ""
for c in uncompressed:
var wc = w & c
if
w = wc
else:
#
# "wc" is a new sequence
dictionary
w = $c
#
▲ compressed.add(dictionary[w])
result = compressed▼
proc decompress*(compressed: var seq[int]): string =
# build the dictionary▼
for i in 0..255:▼
▲ for i in 0..255: dictionary[i] = $chr(i)
compressed.delete(0)
for k in compressed:
var entry: string
entry = dictionary[k]
elif
entry = w & w[0]
else:
raise newException(ValueError, "Bad compressed k: " & $k)
result.add entry
▲ # new sequence; add it to the dictionary
▲ dictionary.add(dictionary.len, w & entry[0])
w = entry
when isMainModule:
Line 3,603 ⟶ 3,592:
echo compressed
var decompressed = decompress(compressed)
echo decompressed</lang>
{{
<pre>@[84, 79, 66, 69, 79, 82, 78, 79, 84, 256, 258, 260, 265, 259, 261, 263]▼
TOBEORNOTTOBEORTOBEORNOT</pre>▼
▲@[84, 79, 66, 69, 79, 82, 78, 79, 84, 256, 258, 260, 265, 259, 261, 263]
▲TOBEORNOTTOBEORTOBEORNOT
=={{header|Objeck}}==
|