LZW compression: Difference between revisions

Content deleted Content added
PureFox (talk | contribs)
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
import tables
 
proc compress*(uncompressed: string): seq[int] =
## build the dictionary
var dictionary = initTable[string, int]()
for i in 0..255:
dictionary.add($char(i), i)
 
## buildBuild the dictionary.
var w: string = newString(0)
var compresseddictionary: = newSeqTable[string, int]()
for i in 0..255: dictionary[$chr(i)] = i
 
var w = ""
for c in uncompressed:
var wc = w & c
if(dictionary.hasKey( wc)) in dictionary:
w = wc
else:
# writesWrites "w" to output.
compressedresult.add( dictionary[w])
# "wc" is a new sequence;: add it to the dictionary.
dictionary.add([wc,] = dictionary.len)
w = $c
 
# writeWrite remaining output if necessary.
if w.len compressed> 0: result.add( dictionary[w])
if(w != nil):
compressed.add(dictionary[w])
 
result = compressed
 
proc decompress*(compressed: var seq[int]): string =
# build the dictionary
var dictionary = initTable[int, string]()
for i in 0..255:
dictionary.add(i, $char(i))
 
var# w:Build string =the dictionary[compressed[0]].
var dictionary: = initTableTable[stringint, intstring]()
for i in 0..255: dictionary[i] = $chr(i)
 
resultvar w = dictionary[compressed[0]]
compressed.delete(0)
 
var decompressedresult = w
 
for k in compressed:
var entry: string = newString(0)
# build theif k in dictionary:
if(dictionary.hasKey(k)):
entry = dictionary[k]
elif( k == dictionary.len):
entry = w & w[0]
else:
raise newException(ValueError, "Bad compressed k: " & $k)
result.add entry
 
# newNew sequence;: add it to the dictionary.
decompressed &= entry
dictionary.add([dictionary.len,] = w & entry[0])
 
# new sequence; add it to the dictionary
dictionary.add(dictionary.len, w & entry[0])
 
w = entry
 
result = decompressed
 
when isMainModule:
Line 3,603 ⟶ 3,592:
echo compressed
var decompressed = decompress(compressed)
echo decompressed</lang>
 
</lang>
{{Outout}}
<pre>@[84, 79, 66, 69, 79, 82, 78, 79, 84, 256, 258, 260, 265, 259, 261, 263]
<pre>
TOBEORNOTTOBEORTOBEORNOT</pre>
@[84, 79, 66, 69, 79, 82, 78, 79, 84, 256, 258, 260, 265, 259, 261, 263]
TOBEORNOTTOBEORTOBEORNOT
</pre>
 
=={{header|Objeck}}==