LZW compression: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 8: Line 8:
=={{header|11l}}==
=={{header|11l}}==
{{trans|Python}}
{{trans|Python}}
<lang 11l>F compress(uncompressed)
<syntaxhighlight lang="11l">F compress(uncompressed)
V dict_size = 256
V dict_size = 256
V dictionary = Dict((0 .< dict_size).map(i -> (String(Char(code' i)), i)))
V dictionary = Dict((0 .< dict_size).map(i -> (String(Char(code' i)), i)))
Line 51: Line 51:
V compressed = compress(‘TOBEORNOTTOBEORTOBEORNOT’)
V compressed = compress(‘TOBEORNOTTOBEORTOBEORNOT’)
print(compressed)
print(compressed)
print(decompress(&compressed))</lang>
print(decompress(&compressed))</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
Line 57: Line 57:


lzw.ads:
lzw.ads:
<lang Ada>package LZW is
<syntaxhighlight lang="ada">package LZW is


MAX_CODE : constant := 4095;
MAX_CODE : constant := 4095;
Line 67: Line 67:
function Decompress (Data : in Compressed_Data) return String;
function Decompress (Data : in Compressed_Data) return String;


end LZW;</lang>
end LZW;</syntaxhighlight>


lzw.adb:
lzw.adb:
<lang Ada>with Ada.Containers.Ordered_Maps;
<syntaxhighlight lang="ada">with Ada.Containers.Ordered_Maps;
with Ada.Strings.Unbounded;
with Ada.Strings.Unbounded;


Line 185: Line 185:
end Decompress;
end Decompress;


end LZW;</lang>
end LZW;</syntaxhighlight>


test.adb:
test.adb:
<lang Ada>with LZW;
<syntaxhighlight lang="ada">with LZW;
with Ada.Text_IO;
with Ada.Text_IO;


Line 208: Line 208:
Text_IO.Put_Line (Cleartext);
Text_IO.Put_Line (Cleartext);
end;
end;
end Test;</lang>
end Test;</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>compress: function [str][
<syntaxhighlight lang="rebol">compress: function [str][
dict: #[]
dict: #[]
loop 0..255 'i -> dict\[to :char i]: i
loop 0..255 'i -> dict\[to :char i]: i
Line 263: Line 263:
decompressed: decompress compressed
decompressed: decompress compressed
print "Decompressed:"
print "Decompressed:"
print decompressed</lang>
print decompressed</syntaxhighlight>


{{out}}
{{out}}
Line 274: Line 274:


=={{header|BaCon}}==
=={{header|BaCon}}==
<lang bacon>CONST lzw_data$ = "TOBEORNOTTOBEORTOBEORNOT"
<syntaxhighlight lang="bacon">CONST lzw_data$ = "TOBEORNOTTOBEORTOBEORNOT"


PRINT "LZWData: ", lzw_data$
PRINT "LZWData: ", lzw_data$
Line 349: Line 349:
RETURN result$
RETURN result$


END FUNCTION</lang>
END FUNCTION</syntaxhighlight>
{{out}}
{{out}}
<pre>LZWData: TOBEORNOTTOBEORTOBEORNOT
<pre>LZWData: TOBEORNOTTOBEORTOBEORNOT
Line 359: Line 359:
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
Uses fixed bit-width (16 bits) and initial dictionary size = 256.
Uses fixed bit-width (16 bits) and initial dictionary size = 256.
<lang bbcbasic> plaintext$ = "TOBEORNOTTOBEORTOBEORNOT"
<syntaxhighlight lang="bbcbasic"> plaintext$ = "TOBEORNOTTOBEORTOBEORNOT"
encodeLZW$ = FNencodeLZW(plaintext$)
encodeLZW$ = FNencodeLZW(plaintext$)
FOR i% = 1 TO LEN(encodeLZW$) STEP 2
FOR i% = 1 TO LEN(encodeLZW$) STEP 2
Line 406: Line 406:
w$ = t$
w$ = t$
NEXT
NEXT
= o$</lang>
= o$</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 421: Line 421:
'''WARNING: This code appears to have come from a GIF codec that has been modified to meet the requirements of this page, provided that the decoder works with the encoder to produce correct output. For writing GIF files the write_bits subroutine is wrong for Little Endian systems (it may be wrong for Big Endian as well.) The encoder also increases the number of bits in the variable length GIF-LZW after the N-2 code, whereas this must be done after N-1 to produce a working GIF file (just looking at the encoder, it's easy to see how this mistake could be made.)'''
'''WARNING: This code appears to have come from a GIF codec that has been modified to meet the requirements of this page, provided that the decoder works with the encoder to produce correct output. For writing GIF files the write_bits subroutine is wrong for Little Endian systems (it may be wrong for Big Endian as well.) The encoder also increases the number of bits in the variable length GIF-LZW after the N-2 code, whereas this must be done after N-1 to produce a working GIF file (just looking at the encoder, it's easy to see how this mistake could be made.)'''


<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <string.h>
#include <string.h>
Line 678: Line 678:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp}}==
=={{header|C sharp}}==
{{trans|Java}}
{{trans|Java}}
<lang C sharp>using System;
<syntaxhighlight lang="c sharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Text;
using System.Text;
Line 762: Line 762:
}
}
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 770: Line 770:
=={{header|C++}}==
=={{header|C++}}==
{{trans|D}}
{{trans|D}}
<lang cpp>#include <string>
<syntaxhighlight lang="cpp">#include <string>
#include <map>
#include <map>


Line 850: Line 850:
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang lisp>(defn make-dict []
<syntaxhighlight lang="lisp">(defn make-dict []
(let [vals (range 0 256)]
(let [vals (range 0 256)]
(zipmap (map (comp #'list #'char) vals) vals)))
(zipmap (map (comp #'list #'char) vals) vals)))
Line 871: Line 871:
(reverse (if w (cons (get dict w) r) r))))))
(reverse (if w (cons (get dict w) r) r))))))


(compress "TOBEORNOTTOBEORTOBEORNOT")</lang>
(compress "TOBEORNOTTOBEORTOBEORNOT")</syntaxhighlight>
{{out}}
{{out}}
<lang lisp>(84 79 66 69 79 82 78 79 84 256 258 260 265 259 261 263)</lang>
<syntaxhighlight lang="lisp">(84 79 66 69 79 82 78 79 84 256 258 260 265 259 261 263)</syntaxhighlight>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
This only does the encoding step for now.
This only does the encoding step for now.


<lang coffeescript>
<syntaxhighlight lang="coffeescript">
lzw = (s) ->
lzw = (s) ->
dct = {} # map substrings to codes between 256 and 4096
dct = {} # map substrings to codes between 256 and 4096
Line 915: Line 915:
console.log lzw "TOBEORNOTTOBEORTOBEORNOT"
console.log lzw "TOBEORNOTTOBEORTOBEORNOT"
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 947: Line 947:
The exact encoding used is dependent upon the user's locale (<code>LC_CTYPE</code> on Unix).
The exact encoding used is dependent upon the user's locale (<code>LC_CTYPE</code> on Unix).


<lang lisp>(declaim (ftype (function (vector vector &optional fixnum fixnum) vector)
<syntaxhighlight lang="lisp">(declaim (ftype (function (vector vector &optional fixnum fixnum) vector)
vector-append))
vector-append))
(defun vector-append (old new &optional (start2 0) end2)
(defun vector-append (old new &optional (start2 0) end2)
Line 1,056: Line 1,056:
(assert (equal #2=(lzw-decompress-to-string (lzw-compress string)) string) ()
(assert (equal #2=(lzw-decompress-to-string (lzw-compress string)) string) ()
"Can't compress ~S properly, got ~S instead" string #2#)
"Can't compress ~S properly, got ~S instead" string #2#)
t)</lang>
t)</syntaxhighlight>


And the format used:
And the format used:


<lang lisp>CL-USER> (test "TOBEORNOTTOBEORTOBEORNOT")
<syntaxhighlight lang="lisp">CL-USER> (test "TOBEORNOTTOBEORTOBEORNOT")
T
T
CL-USER> (lzw-compress "TOBEORNOTTOBEORTOBEORNOT")
CL-USER> (lzw-compress "TOBEORNOTTOBEORTOBEORNOT")
#(84 79 66 69 79 82 78 79 84 256 258 260 265 259 261 263)
#(84 79 66 69 79 82 78 79 84 256 258 260 265 259 261 263)
CL-USER> (lzw-decompress-to-string *)
CL-USER> (lzw-decompress-to-string *)
"TOBEORNOTTOBEORTOBEORNOT"</lang>
"TOBEORNOTTOBEORTOBEORNOT"</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
===Simpler Version===
===Simpler Version===
<lang d>import std.stdio, std.array;
<syntaxhighlight lang="d">import std.stdio, std.array;


auto compress(in string original) pure nothrow {
auto compress(in string original) pure nothrow {
Line 1,108: Line 1,108:
auto comp = "TOBEORNOTTOBEORTOBEORNOT".compress;
auto comp = "TOBEORNOTTOBEORTOBEORNOT".compress;
writeln(comp, "\n", comp.decompress);
writeln(comp, "\n", comp.decompress);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[84, 79, 66, 69, 79, 82, 78, 79, 84, 256, 258, 260, 265, 259, 261, 263]
<pre>[84, 79, 66, 69, 79, 82, 78, 79, 84, 256, 258, 260, 265, 259, 261, 263]
Line 1,115: Line 1,115:
===More Refined Version===
===More Refined Version===
This longer version is a little more efficient and it uses stronger static typing.
This longer version is a little more efficient and it uses stronger static typing.
<lang d>struct LZW {
<syntaxhighlight lang="d">struct LZW {
import std.array: empty;
import std.array: empty;


Line 1,209: Line 1,209:
compressed.writeln;
compressed.writeln;
LZW.decompress(compressed).assumeUTF.writeln;
LZW.decompress(compressed).assumeUTF.writeln;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[84, 79, 66, 69, 79, 82, 78, 79, 84, 256, 258, 260, 265, 259, 261, 263]
<pre>[84, 79, 66, 69, 79, 82, 78, 79, 84, 256, 258, 260, 265, 259, 261, 263]
Line 1,217: Line 1,217:
{{trans|C}}
{{trans|C}}
This code retains part of the style of the original C code.
This code retains part of the style of the original C code.
<lang d>enum Marker: ushort {
<syntaxhighlight lang="d">enum Marker: ushort {
CLR = 256, // Clear table marker.
CLR = 256, // Clear table marker.
EOD = 257, // End-of-data marker.
EOD = 257, // End-of-data marker.
Line 1,438: Line 1,438:


"Decoded OK.".writeln;
"Decoded OK.".writeln;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Input size: 206403
<pre>Input size: 206403
Line 1,446: Line 1,446:


=={{header|Dylan}}==
=={{header|Dylan}}==
<lang dylan>Module: LZW
<syntaxhighlight lang="dylan">Module: LZW
Synopsis: LZW implementation for Rosetta code
Synopsis: LZW implementation for Rosetta code


Line 1,488: Line 1,488:
end;
end;


format-out("%=\n", compress("TOBEORNOTTOBEORTOBEORNOT"))</lang>
format-out("%=\n", compress("TOBEORNOTTOBEORTOBEORNOT"))</syntaxhighlight>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
class
APPLICATION
APPLICATION
Line 1,604: Line 1,604:


end
end
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,613: Line 1,613:
=={{header|Elixir}}==
=={{header|Elixir}}==
{{trans|Erlang}}
{{trans|Erlang}}
<lang elixir>defmodule LZW do
<syntaxhighlight lang="elixir">defmodule LZW do
@encode_map Enum.into(0..255, Map.new, &{[&1],&1})
@encode_map Enum.into(0..255, Map.new, &{[&1],&1})
@decode_map Enum.into(0..255, Map.new, &{&1,[&1]})
@decode_map Enum.into(0..255, Map.new, &{&1,[&1]})
Line 1,651: Line 1,651:
IO.inspect enc = LZW.encode(str)
IO.inspect enc = LZW.encode(str)
IO.inspect dec = LZW.decode(enc)
IO.inspect dec = LZW.decode(enc)
IO.inspect str == dec</lang>
IO.inspect str == dec</syntaxhighlight>


{{out}}
{{out}}
Line 1,661: Line 1,661:


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>-module(lzw).
<syntaxhighlight lang="erlang">-module(lzw).


-export([test/0, encode/1, decode/1]).
-export([test/0, encode/1, decode/1]).
Line 1,717: Line 1,717:


init1(0, D) -> D;
init1(0, D) -> D;
init1(N, D) -> D1 = dict:store(N,[N],D), init1(N-1, D1).</lang>
init1(N, D) -> D1 = dict:store(N,[N],D), init1(N-1, D1).</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
{{works with|GNU Forth|0.6.2}}
{{works with|GNU Forth|0.6.2}}
<lang forth>256 value next-symbol
<syntaxhighlight lang="forth">256 value next-symbol


\ current string fragment
\ current string fragment
Line 1,819: Line 1,819:


out out-size @ decompress cr
out out-size @ decompress cr
\ TOBEORNOTTOBEORTOBEORNOT</lang>
\ TOBEORNOTTOBEORTOBEORNOT</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
<syntaxhighlight lang="fortran">
<lang Fortran>
!
!
! lzw_shared_parameters.f90
! lzw_shared_parameters.f90
Line 2,244: Line 2,244:
CALL CPU_TIME(finish)
CALL CPU_TIME(finish)
PRINT '("Time = ",f6.3," seconds.")' , finish - start
PRINT '("Time = ",f6.3," seconds.")' , finish - start
END PROGRAM MAIN</lang>
END PROGRAM MAIN</syntaxhighlight>
=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' version 22-02-2019
<syntaxhighlight lang="freebasic">' version 22-02-2019
' compile with: fbc -s console
' compile with: fbc -s console


Line 2,355: Line 2,355:
Print : Print "hit any key to end program"
Print : Print "hit any key to end program"
Sleep
Sleep
End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre> input str: TOBEORNOTTOBEORTOBEORNOT
<pre> input str: TOBEORNOTTOBEORTOBEORNOT
Line 2,370: Line 2,370:
not just ASCII or valid UTF8 encoding
not just ASCII or valid UTF8 encoding
(tested with [https://github.com/dvyukov/go-fuzz go-fuzz]).
(tested with [https://github.com/dvyukov/go-fuzz go-fuzz]).
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 2,464: Line 2,464:
}
}
fmt.Println(decompressed)
fmt.Println(decompressed)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,472: Line 2,472:


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang groovy>def compress = { text ->
<syntaxhighlight lang="groovy">def compress = { text ->
def dictionary = (0..<256).inject([:]) { map, ch -> map."${(char)ch}" = ch; map }
def dictionary = (0..<256).inject([:]) { map, ch -> map."${(char)ch}" = ch; map }
def w = '', compressed = []
def w = '', compressed = []
Line 2,508: Line 2,508:


result.toString()
result.toString()
}</lang>
}</syntaxhighlight>
Testing:
Testing:
<lang groovy>def plaintext = 'TOBEORNOTTOBEORTOBEORNOT'
<syntaxhighlight lang="groovy">def plaintext = 'TOBEORNOTTOBEORTOBEORNOT'
def compressed = compress(plaintext)
def compressed = compress(plaintext)
def result = decompress(compressed)
def result = decompress(compressed)
Line 2,517: Line 2,517:
Plaintext: '$plaintext'
Plaintext: '$plaintext'
Compressed: $compressed
Compressed: $compressed
Uncompressed: '$result'""".stripIndent()</lang>
Uncompressed: '$result'""".stripIndent()</syntaxhighlight>
{{out}}
{{out}}
<pre>Plaintext: 'TOBEORNOTTOBEORTOBEORNOT'
<pre>Plaintext: 'TOBEORNOTTOBEORTOBEORNOT'
Line 2,525: Line 2,525:
=={{header|Haskell}}==
=={{header|Haskell}}==


<lang Haskell>import Data.List (elemIndex, tails)
<syntaxhighlight lang="haskell">import Data.List (elemIndex, tails)
import Data.Maybe (fromJust)
import Data.Maybe (fromJust)


Line 2,562: Line 2,562:
print $
print $
((==) <*> ((.) <$> undoLZW <*> doLZW) ['\NUL' .. '\255'])
((==) <*> ((.) <$> undoLZW <*> doLZW) ['\NUL' .. '\255'])
"TOBEORNOTTOBEORTOBEORNOT"</lang>
"TOBEORNOTTOBEORTOBEORNOT"</syntaxhighlight>
{{Out}}
{{Out}}
<pre>[84,79,66,69,79,82,78,79,84,256,258,260,265,259,261,263]
<pre>[84,79,66,69,79,82,78,79,84,256,258,260,265,259,261,263]
Line 2,573: Line 2,573:


Straightforward implementations of encoding and decoding:
Straightforward implementations of encoding and decoding:
<lang J>encodeLZW =: 4 : 0
<syntaxhighlight lang="j">encodeLZW =: 4 : 0
d=. ;/x
d=. ;/x
r=.0$0
r=.0$0
Line 2,586: Line 2,586:
end.
end.
r, d i.<w
r, d i.<w
)</lang>
)</syntaxhighlight>
Test:
Test:
<pre> a. encodeLZW 'TOBEORNOTTOBEORTOBEORNOT'
<pre> a. encodeLZW 'TOBEORNOTTOBEORTOBEORNOT'
84 79 66 69 79 82 78 79 84 256 258 260 265 259 261 263</pre>
84 79 66 69 79 82 78 79 84 256 258 260 265 259 261 263</pre>
Decoding:
Decoding:
<lang J>decodeLZW =: 4 : 0
<syntaxhighlight lang="j">decodeLZW =: 4 : 0
d=.;/x
d=.;/x
w=.r=. >d{~{.y
w=.r=. >d{~{.y
Line 2,606: Line 2,606:
end.
end.
;r
;r
)</lang>
)</syntaxhighlight>
Test:
Test:
<pre> a. decodeLZW 84 79 66 69 79 82 78 79 84 256 258 260 265 259 261 263
<pre> a. decodeLZW 84 79 66 69 79 82 78 79 84 256 258 260 265 259 261 263
Line 2,624: Line 2,624:
=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
<lang java5>import java.util.*;
<syntaxhighlight lang="java5">import java.util.*;


public class LZW {
public class LZW {
Line 2,690: Line 2,690:
System.out.println(decompressed);
System.out.println(decompressed);
}
}
}</lang>
}</syntaxhighlight>


{{out}} (Command Line direct output):
{{out}} (Command Line direct output):
<lang java5>[84, 79, 66, 69, 79, 82, 78, 79, 84, 256, 258, 260, 265, 259, 261, 263]
<syntaxhighlight lang="java5">[84, 79, 66, 69, 79, 82, 78, 79, 84, 256, 258, 260, 265, 259, 261, 263]
TOBEORNOTTOBEORTOBEORNOT</lang>
TOBEORNOTTOBEORTOBEORNOT</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
<lang javascript>//LZW Compression/Decompression for Strings
<syntaxhighlight lang="javascript">//LZW Compression/Decompression for Strings
var LZW = {
var LZW = {
compress: function (uncompressed) {
compress: function (uncompressed) {
Line 2,777: Line 2,777:
comp = LZW.compress("TOBEORNOTTOBEORTOBEORNOT"),
comp = LZW.compress("TOBEORNOTTOBEORTOBEORNOT"),
decomp = LZW.decompress(comp);
decomp = LZW.decompress(comp);
document.write(comp + '<br>' + decomp);</lang>
document.write(comp + '<br>' + decomp);</syntaxhighlight>




Line 2,784: Line 2,784:
This is the the same thing, but for ES6. The code has been refactored and cleaned up a bit to look neater.
This is the the same thing, but for ES6. The code has been refactored and cleaned up a bit to look neater.


<lang javascript>'use strict';
<syntaxhighlight lang="javascript">'use strict';
/**
/**
Namespace for LZW compression and decompression.
Namespace for LZW compression and decompression.
Line 2,893: Line 2,893:


console.log(`${comp}
console.log(`${comp}
${decomp}`);</lang>
${decomp}`);</syntaxhighlight>


{{out}}
{{out}}
Line 2,902: Line 2,902:
{{ works with|jq|1.4}}
{{ works with|jq|1.4}}
{{trans|JavaScript}}
{{trans|JavaScript}}
<lang jq># LZW compression/decompression for strings
<syntaxhighlight lang="jq"># LZW compression/decompression for strings
def lzw_compress:
def lzw_compress:
def decode: [.] | implode;
def decode: [.] | implode;
Line 2,947: Line 2,947:
| .[2] = $entry # w = entry
| .[2] = $entry # w = entry
) | .[3]
) | .[3]
;</lang>
;</syntaxhighlight>
'''Example''':
'''Example''':
<lang jq>"TOBEORNOTTOBEORTOBEORNOT" | lzw_compress| lzw_decompress</lang>
<syntaxhighlight lang="jq">"TOBEORNOTTOBEORTOBEORNOT" | lzw_compress| lzw_decompress</syntaxhighlight>
{{Out}}
{{Out}}
$ jq -n -f LZW.jq
$ jq -n -f LZW.jq
Line 2,956: Line 2,956:
=={{header|Julia}}==
=={{header|Julia}}==
{{works with|Julia|1.1.1}}
{{works with|Julia|1.1.1}}
<lang julia>function compressLZW(decompressed::String)
<syntaxhighlight lang="julia">function compressLZW(decompressed::String)
dictsize = 256
dictsize = 256
dict = Dict{String,Int}(string(Char(i)) => i for i in 0:dictsize)
dict = Dict{String,Int}(string(Char(i)) => i for i in 0:dictsize)
Line 3,005: Line 3,005:
comprate = (length(word) - length(comp)) / length(word) * 100
comprate = (length(word) - length(comp)) / length(word) * 100
println("Original: $word\n-> Compressed: $comp (compr.rate: $(round(comprate, digits=2))%)\n-> Decompressed: $decomp")
println("Original: $word\n-> Compressed: $comp (compr.rate: $(round(comprate, digits=2))%)\n-> Decompressed: $decomp")
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 3,020: Line 3,020:
=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|Java}}
{{trans|Java}}
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


object Lzw {
object Lzw {
Line 3,081: Line 3,081:
val decompressed = Lzw.decompress(compressed)
val decompressed = Lzw.decompress(compressed)
println(decompressed)
println(decompressed)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,094: Line 3,094:
It also has the option to write the encoding/decoding dictionaries to file so the encoder can be checked for accuracy.
It also has the option to write the encoding/decoding dictionaries to file so the encoder can be checked for accuracy.
This code directly follows the methodology described in an excellent web article by Juha Nieminen entitled "An efficient LZW implementation".
This code directly follows the methodology described in an excellent web article by Juha Nieminen entitled "An efficient LZW implementation".
<lang> DIM LZW(1, 1)
<syntaxhighlight lang="text"> DIM LZW(1, 1)
DIM JDlzw(1)
DIM JDlzw(1)
DIM JDch$(1)
DIM JDch$(1)
Line 3,373: Line 3,373:
fileTag$ = STR$(tagCount) + "_"
fileTag$ = STR$(tagCount) + "_"
RETURN
RETURN
''''''''''''''''''''''''''''''''''''''''</lang>
''''''''''''''''''''''''''''''''''''''''</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==


<lang lua>local function compress(uncompressed) -- string
<syntaxhighlight lang="lua">local function compress(uncompressed) -- string
local dictionary, result, dictSize, w, c = {}, {}, 255, ""
local dictionary, result, dictSize, w, c = {}, {}, 255, ""
for i = 0, 255 do
for i = 0, 255 do
Line 3,426: Line 3,426:
local dec = decompress(com)
local dec = decompress(com)
print(table.concat(com, ", "))
print(table.concat(com, ", "))
print(dec)</lang>
print(dec)</syntaxhighlight>


{{Out}}
{{Out}}
Line 3,436: Line 3,436:
=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
{{trans|BBC BASIC}}
{{trans|BBC BASIC}}
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module BBCtrans {
Module BBCtrans {
\\ LZW compression
\\ LZW compression
Line 3,489: Line 3,489:
}
}
BBCtrans
BBCtrans
</syntaxhighlight>
</lang>


And here a change for using Inventories, where we have hash function, and we find entry in O(1).
And here a change for using Inventories, where we have hash function, and we find entry in O(1).
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module FastM2000 {
Module FastM2000 {
plaintext$="TOBEORNOTTOBEORTOBEORNOT"
plaintext$="TOBEORNOTTOBEORTOBEORNOT"
Line 3,550: Line 3,550:
}
}
FastM2000
FastM2000
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre >
<pre >
Line 3,559: Line 3,559:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
{{trans|Ruby}}
{{trans|Ruby}}
<lang>compress[uncompressed_] :=
<syntaxhighlight lang="text">compress[uncompressed_] :=
Module[{dictsize, dictionary, w, result, wc},
Module[{dictsize, dictionary, w, result, wc},
dictsize = 256;
dictsize = 256;
Line 3,595: Line 3,595:
(*How to use:*)
(*How to use:*)
compress["TOBEORNOTTOBEORTOBEORNOT"]
compress["TOBEORNOTTOBEORTOBEORNOT"]
decompress[%]</lang>
decompress[%]</syntaxhighlight>
{{Out}}
{{Out}}
<pre>{"T", "O", "B", "E", "O", "R", "N", "O", "T", 256, 258, 260, 265, 259, 261, 263}
<pre>{"T", "O", "B", "E", "O", "R", "N", "O", "T", 256, 258, 260, 265, 259, 261, 263}
Line 3,603: Line 3,603:


=={{header|Nim}}==
=={{header|Nim}}==
<lang>import tables
<syntaxhighlight lang="text">import tables


proc compress*(uncompressed: string): seq[int] =
proc compress*(uncompressed: string): seq[int] =
Line 3,655: Line 3,655:
echo compressed
echo compressed
var decompressed = decompress(compressed)
var decompressed = decompress(compressed)
echo decompressed</lang>
echo decompressed</syntaxhighlight>


{{out}}
{{out}}
Line 3,663: Line 3,663:
=={{header|Objeck}}==
=={{header|Objeck}}==
{{trans|Java}}
{{trans|Java}}
<lang objeck>use Collection;
<syntaxhighlight lang="objeck">use Collection;


class LZW {
class LZW {
Line 3,766: Line 3,766:
"]"->PrintLine();
"]"->PrintLine();
}
}
}</lang>
}</syntaxhighlight>


<pre>[84, 79, 66, 69, 79, 82, 78, 79, 84, 256, 258, 260, 265, 259, 261, 263]
<pre>[84, 79, 66, 69, 79, 82, 78, 79, 84, 256, 258, 260, 265, 259, 261, 263]
Line 3,777: Line 3,777:
The class for the LZW compression algorithm:
The class for the LZW compression algorithm:


<lang objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>
#import <stdio.h>
#import <stdio.h>


Line 3,862: Line 3,862:
}
}


@end</lang>
@end</syntaxhighlight>


Usage example:
Usage example:


<lang objc>NSString *text = @"TOBEORNOTTOBEORTOBEORNOT";
<syntaxhighlight lang="objc">NSString *text = @"TOBEORNOTTOBEORTOBEORNOT";


int main()
int main()
Line 3,886: Line 3,886:
}
}
return EXIT_SUCCESS;
return EXIT_SUCCESS;
}</lang>
}</syntaxhighlight>


{{out}} (reformatted by hand):
{{out}} (reformatted by hand):
Line 3,896: Line 3,896:
=={{header|OCaml}}==
=={{header|OCaml}}==


<lang ocaml>#directory "+extlib" (* or maybe "+site-lib/extlib/" *)
<syntaxhighlight lang="ocaml">#directory "+extlib" (* or maybe "+site-lib/extlib/" *)
#load "extLib.cma"
#load "extLib.cma"
open ExtString
open ExtString
Line 3,975: Line 3,975:
in
in
(List.rev result)
(List.rev result)
;;</lang>
;;</syntaxhighlight>


here is the interface:
here is the interface:
<lang ocaml>val compress : uncompressed:string -> int list
<syntaxhighlight lang="ocaml">val compress : uncompressed:string -> int list
val decompress : compressed:int list -> string list</lang>
val decompress : compressed:int list -> string list</syntaxhighlight>


How to use:<br />
How to use:<br />
Line 3,985: Line 3,985:
So to know how many bits are required, you need to know how many bits are required for the greatest symbol in the list.
So to know how many bits are required, you need to know how many bits are required for the greatest symbol in the list.


<lang ocaml>let greatest = List.fold_left max 0 ;;
<syntaxhighlight lang="ocaml">let greatest = List.fold_left max 0 ;;


(** number of bits needed to encode the integer m *)
(** number of bits needed to encode the integer m *)
Line 4,023: Line 4,023:
List.iter (Buffer.add_string buf) result;
List.iter (Buffer.add_string buf) result;
(Buffer.contents buf)
(Buffer.contents buf)
;;</lang>
;;</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
This version use lazy streams which is pair (symbol . function-to-get-next-symbol).
This version use lazy streams which is pair (symbol . function-to-get-next-symbol).
<lang scheme>
<syntaxhighlight lang="scheme">
(define (compress str)
(define (compress str)
(let loop ((dc (fold (lambda (f x) ; dictionary (simplest, not optimized), with reversed codes
(let loop ((dc (fold (lambda (f x) ; dictionary (simplest, not optimized), with reversed codes
Line 4,053: Line 4,053:


(print (compress "TOBEORNOTTOBEORTOBEORNOT")) ; => (84 79 66 69 79 82 78 79 84 256 258 260 265 259 261 263)
(print (compress "TOBEORNOTTOBEORTOBEORNOT")) ; => (84 79 66 69 79 82 78 79 84 256 258 260 265 259 261 263)
</syntaxhighlight>
</lang>


And decoder (runes->string used to unify functions - both used string iterators):
And decoder (runes->string used to unify functions - both used string iterators):
<lang scheme>
<syntaxhighlight lang="scheme">
(define (decompress str)
(define (decompress str)
(let loop ((dc (fold (lambda (f x) ; dictionary (simplest, not optimized), with reversed codes
(let loop ((dc (fold (lambda (f x) ; dictionary (simplest, not optimized), with reversed codes
Line 4,084: Line 4,084:
(decompress (runes->string '(84 79 66 69 79 82 78 79 84 256 258 260 265 259 261 263)))))
(decompress (runes->string '(84 79 66 69 79 82 78 79 84 256 258 260 265 259 261 263)))))
; => TOBEORNOTTOBEORTOBEEORNOT
; => TOBEORNOTTOBEORTOBEEORNOT
</syntaxhighlight>
</lang>


=={{header|Perl}}==
=={{header|Perl}}==


In this version the hashes contain mixed typed data:
In this version the hashes contain mixed typed data:
<lang perl># Compress a string to a list of output symbols.
<syntaxhighlight lang="perl"># Compress a string to a list of output symbols.
sub compress {
sub compress {
my $uncompressed = shift;
my $uncompressed = shift;
Line 4,153: Line 4,153:
print "@compressed\n";
print "@compressed\n";
my $decompressed = decompress(@compressed);
my $decompressed = decompress(@compressed);
print "$decompressed\n";</lang>
print "$decompressed\n";</syntaxhighlight>


{{out}}
{{out}}
Line 4,163: Line 4,163:
=={{header|Phix}}==
=={{header|Phix}}==
{{trans|Lua}}
{{trans|Lua}}
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">compress</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">uncompressed</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">compress</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">uncompressed</span><span style="color: #0000FF;">)</span>
Line 4,221: Line 4,221:
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">com</span><span style="color: #0000FF;">,{</span><span style="color: #004600;">pp_IntCh</span><span style="color: #0000FF;">,</span><span style="color: #004600;">true</span><span style="color: #0000FF;">,</span><span style="color: #004600;">pp_Maxlen</span><span style="color: #0000FF;">,</span><span style="color: #000000;">90</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">com</span><span style="color: #0000FF;">,{</span><span style="color: #004600;">pp_IntCh</span><span style="color: #0000FF;">,</span><span style="color: #004600;">true</span><span style="color: #0000FF;">,</span><span style="color: #004600;">pp_Maxlen</span><span style="color: #0000FF;">,</span><span style="color: #000000;">90</span><span style="color: #0000FF;">})</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">decompress</span><span style="color: #0000FF;">(</span><span style="color: #000000;">com</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">decompress</span><span style="color: #0000FF;">(</span><span style="color: #000000;">com</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 4,230: Line 4,230:
=={{header|PHP}}==
=={{header|PHP}}==
{{trans|JavaScript}}
{{trans|JavaScript}}
<lang PHP>class LZW
<syntaxhighlight lang="php">class LZW
{
{
function compress($unc) {
function compress($unc) {
Line 4,294: Line 4,294:
$dec = $lzw->decompress($com);
$dec = $lzw->decompress($com);
echo $com . "<br>" . $dec;
echo $com . "<br>" . $dec;
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 4,302: Line 4,302:


=={{header|Picat}}==
=={{header|Picat}}==
<lang Picat>go =>
<syntaxhighlight lang="picat">go =>
S = "TOBEORNOTTOBEORTOBEORNOT",
S = "TOBEORNOTTOBEORTOBEORNOT",
println(s=S),
println(s=S),
Line 4,386: Line 4,386:
edit(Xs,Ys,D1,Diffs1),
edit(Xs,Ys,D1,Diffs1),
D=D1+1,
D=D1+1,
Diffs = [[delete=X,xPos=Xs.length,yPos=Ys.length]|Diffs1].</lang>
Diffs = [[delete=X,xPos=Xs.length,yPos=Ys.length]|Diffs1].</syntaxhighlight>


{{out}}
{{out}}
Line 4,398: Line 4,398:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de lzwCompress (Lst)
<syntaxhighlight lang="picolisp">(de lzwCompress (Lst)
(let (Codes 255 Dict)
(let (Codes 255 Dict)
(balance 'Dict
(balance 'Dict
Line 4,428: Line 4,428:
(when W
(when W
(idx 'Dict (cons (inc 'Codes) (cons (last WC) W)) T) )
(idx 'Dict (cons (inc 'Codes) (cons (last WC) W)) T) )
(setq W WC) ) ) ) ) ) )</lang>
(setq W WC) ) ) ) ) ) )</syntaxhighlight>
Test:
Test:
<pre>: (lzwCompress (chop "TOBEORNOTTOBEORTOBEORNOT"))
<pre>: (lzwCompress (chop "TOBEORNOTTOBEORTOBEORNOT"))
Line 4,439: Line 4,439:
{{trans|REXX}}
{{trans|REXX}}
The interesting point is the implementation of REXX's associative array (compound variable).
The interesting point is the implementation of REXX's associative array (compound variable).
<lang pli>*process source xref attributes or(!);
<syntaxhighlight lang="pli">*process source xref attributes or(!);
lzwt: Proc Options(main);
lzwt: Proc Options(main);


Line 4,588: Line 4,588:
Return;
Return;


End;</lang>
End;</syntaxhighlight>
{{out}}
{{out}}
<pre>str=TOBEORNOTTOBEORTOBEORNOT
<pre>str=TOBEORNOTTOBEORTOBEORNOT
Line 4,600: Line 4,600:
This is because PureBasic uses these to terminate strings.
This is because PureBasic uses these to terminate strings.
Only slight modifications are necessary to handle Null values that would be present for a more generic routine that could be used with a buffer containing any data type.
Only slight modifications are necessary to handle Null values that would be present for a more generic routine that could be used with a buffer containing any data type.
<lang PureBasic>Procedure compress(uncompressed.s, List result.u())
<syntaxhighlight lang="purebasic">Procedure compress(uncompressed.s, List result.u())
;Compress a string to a list of output symbols
;Compress a string to a list of output symbols
Line 4,696: Line 4,696:
Input()
Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>
Sample output:
Sample output:
<pre>Type something: TOBEORNOTTOBEORTOBEORNOT
<pre>Type something: TOBEORNOTTOBEORTOBEORNOT
Line 4,705: Line 4,705:
{{works with|Python|3.x}}
{{works with|Python|3.x}}
In this version the dicts contain mixed typed data:
In this version the dicts contain mixed typed data:
<lang python>def compress(uncompressed):
<syntaxhighlight lang="python">def compress(uncompressed):
"""Compress a string to a list of output symbols."""
"""Compress a string to a list of output symbols."""


Line 4,767: Line 4,767:
print (compressed)
print (compressed)
decompressed = decompress(compressed)
decompressed = decompress(compressed)
print (decompressed)</lang>
print (decompressed)</syntaxhighlight>


Output:
Output:
Line 4,776: Line 4,776:


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
; utilities
; utilities
Line 4,834: Line 4,834:
(def decompressed (decompress compressed))
(def decompressed (decompress compressed))
(displayln decompressed)
(displayln decompressed)
</syntaxhighlight>
</lang>


Output:
Output:
Line 4,846: Line 4,846:
(formerly Perl 6) I just came across [https://stackoverflow.com/questions/30531078/ this SO question] by chance hence the update. Notably the ancestor Perl entry simply works without any further tweak.
(formerly Perl 6) I just came across [https://stackoverflow.com/questions/30531078/ this SO question] by chance hence the update. Notably the ancestor Perl entry simply works without any further tweak.
{{trans|Perl}}
{{trans|Perl}}
<lang perl6># 20200421 Updated Raku programming solution ; add unicode support
<syntaxhighlight lang="raku" line># 20200421 Updated Raku programming solution ; add unicode support


sub compress(Str $uncompressed --> Seq) {
sub compress(Str $uncompressed --> Seq) {
Line 4,891: Line 4,891:


@compressed = compress('こんにちは𝒳𝒴𝒵こんにちは𝒳𝒴𝒵こんにちは𝒳𝒴𝒵');
@compressed = compress('こんにちは𝒳𝒴𝒵こんにちは𝒳𝒴𝒵こんにちは𝒳𝒴𝒵');
say decompress(@compressed);</lang>
say decompress(@compressed);</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,902: Line 4,902:
===version 1===
===version 1===
{{trans|Java}}
{{trans|Java}}
<lang rexx>/* REXX ---------------------------------------------------------------
<syntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* 20.07.2014 Walter Pachl translated from Java
* 20.07.2014 Walter Pachl translated from Java
* 21.07.2014 WP allow for blanks in the string
* 21.07.2014 WP allow for blanks in the string
Line 4,977: Line 4,977:
w=entry
w=entry
End
End
Return res</lang>
Return res</syntaxhighlight>
'''Output:'''
'''Output:'''
<pre>str=TOBEORNOTTOBEORTOBEORNOT
<pre>str=TOBEORNOTTOBEORTOBEORNOT
Line 4,995: Line 4,995:


This REXX version can execute on &nbsp; '''ASCII''' &nbsp; or &nbsp; '''EBCDIC''' &nbsp; systems.
This REXX version can execute on &nbsp; '''ASCII''' &nbsp; or &nbsp; '''EBCDIC''' &nbsp; systems.
<lang rexx>/*REXX program compresses text using the LZW (Lempel─Ziv─Welch), and reconstitutes it.*/
<syntaxhighlight lang="rexx">/*REXX program compresses text using the LZW (Lempel─Ziv─Welch), and reconstitutes it.*/
$$$= '"There is nothing permanent except change." ─── Heraclitus [540 ── 475 BCE]'
$$$= '"There is nothing permanent except change." ─── Heraclitus [540 ── 475 BCE]'
parse arg text; if text='' then text= $$$ /*get an optional argument from the CL.*/
parse arg text; if text='' then text= $$$ /*get an optional argument from the CL.*/
Line 5,018: Line 5,018:
$= $ || ?
$= $ || ?
@.#= w || left(?, 1); w= ?; #= # + 1 /*bump dict. size*/
@.#= w || left(?, 1); w= ?; #= # + 1 /*bump dict. size*/
end /*k*/; return $</lang>
end /*k*/; return $</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
{{out|output|text=&nbsp; when using the default input:}}
<pre>
<pre>
Line 5,028: Line 5,028:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Project : LZW compression
# Project : LZW compression


Line 5,107: Line 5,107:
svect = left(svect, len(svect) - 1)
svect = left(svect, len(svect) - 1)
see svect + nl
see svect + nl
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 5,117: Line 5,117:


In this version the hashes contain mixed typed data:
In this version the hashes contain mixed typed data:
<lang ruby># Compress a string to a list of output symbols.
<syntaxhighlight lang="ruby"># Compress a string to a list of output symbols.
def compress(uncompressed)
def compress(uncompressed)
# Build the dictionary.
# Build the dictionary.
Line 5,173: Line 5,173:
p compressed
p compressed
decompressed = decompress(compressed)
decompressed = decompress(compressed)
puts decompressed</lang>
puts decompressed</syntaxhighlight>


Output:
Output:
Line 5,184: Line 5,184:
{{trans|C Sharp}}
{{trans|C Sharp}}
Handles arbitrary byte sequences.
Handles arbitrary byte sequences.
<lang rust>use std::collections::HashMap;
<syntaxhighlight lang="rust">use std::collections::HashMap;


fn compress(data: &[u8]) -> Vec<u32> {
fn compress(data: &[u8]) -> Vec<u32> {
Line 5,260: Line 5,260:
let decompressed = String::from_utf8(decompressed).unwrap();
let decompressed = String::from_utf8(decompressed).unwrap();
println!("{}", decompressed);
println!("{}", decompressed);
}</lang>
}</syntaxhighlight>


Output:
Output:
Line 5,269: Line 5,269:


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>
<syntaxhighlight lang="scala">
def compress(tc:String) = {
def compress(tc:String) = {
//initial dictionary
//initial dictionary
Line 5,315: Line 5,315:
val result = decompress(compressed)
val result = decompress(compressed)
println(result)
println(result)
</syntaxhighlight>
</lang>


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>; Get the list reference number for a member or #f if not found
<syntaxhighlight lang="scheme">; Get the list reference number for a member or #f if not found
(define (member-string-ref m l)
(define (member-string-ref m l)
(define r #f)
(define r #f)
Line 5,402: Line 5,402:
(display compressed) (newline)
(display compressed) (newline)
(define decompressed (lzw-decompress compressed))
(define decompressed (lzw-decompress compressed))
(display decompressed) (newline)</lang>
(display decompressed) (newline)</syntaxhighlight>
Output:<pre>(84 79 66 69 79 82 78 79 84 256 258 260 265 259 261 263)
Output:<pre>(84 79 66 69 79 82 78 79 84 256 258 260 265 259 261 263)
TOBEORNOTTOBEORTOBEORNOT</pre>
TOBEORNOTTOBEORTOBEORNOT</pre>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
const func string: lzwCompress (in string: uncompressed) is func
const func string: lzwCompress (in string: uncompressed) is func
Line 5,481: Line 5,481:
uncompressed := lzwDecompress(compressed);
uncompressed := lzwDecompress(compressed);
writeln(uncompressed);
writeln(uncompressed);
end func;</lang>
end func;</syntaxhighlight>


Output:
Output:
Line 5,493: Line 5,493:
=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Perl}}
{{trans|Perl}}
<lang ruby># Compress a string to a list of output symbols.
<syntaxhighlight lang="ruby"># Compress a string to a list of output symbols.
func compress(String uncompressed) -> Array {
func compress(String uncompressed) -> Array {
Line 5,564: Line 5,564:
say compressed.join(' ')
say compressed.join(' ')
var decompressed = decompress(compressed)
var decompressed = decompress(compressed)
say decompressed</lang>
say decompressed</syntaxhighlight>
{{out}}
{{out}}
<pre>T O B E O R N O T 256 258 260 265 259 261 263
<pre>T O B E O R N O T 256 258 260 265 259 261 263
Line 5,571: Line 5,571:
=={{header|Swift}}==
=={{header|Swift}}==
{{trans|JavaScript}}
{{trans|JavaScript}}
<lang swift>class LZW {
<syntaxhighlight lang="swift">class LZW {
class func compress(_ uncompressed:String) -> [Int] {
class func compress(_ uncompressed:String) -> [Int] {
var dict = [String : Int]()
var dict = [String : Int]()
Line 5,635: Line 5,635:
if let decomp = LZW.decompress(comp) {
if let decomp = LZW.decompress(comp) {
print(decomp)
print(decomp)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 5,643: Line 5,643:


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>namespace eval LZW {
<syntaxhighlight lang="tcl">namespace eval LZW {
variable char2int
variable char2int
variable chars
variable chars
Line 5,702: Line 5,702:


# or
# or
if {$s eq [LZW::decode [LZW::encode $s]]} then {puts success} else {puts fail} ;# ==> success</lang>
if {$s eq [LZW::decode [LZW::encode $s]]} then {puts success} else {puts fail} ;# ==> success</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang ecmascript>class LZW {
<syntaxhighlight lang="ecmascript">class LZW {
/* Compress a string to a list of output symbols. */
/* Compress a string to a list of output symbols. */
static compress(uncompressed) {
static compress(uncompressed) {
Line 5,765: Line 5,765:
System.print(compressed)
System.print(compressed)
var decompressed = LZW.decompress(compressed)
var decompressed = LZW.decompress(compressed)
System.print(decompressed)</lang>
System.print(decompressed)</syntaxhighlight>


{{out}}
{{out}}
Line 5,775: Line 5,775:
=={{header|Xojo}}==
=={{header|Xojo}}==
{{trans|PHP}}
{{trans|PHP}}
<syntaxhighlight lang="vb">
<lang vb>
Function compress(str as String) As String
Function compress(str as String) As String
Dim i as integer
Dim i as integer
Line 5,882: Line 5,882:
End Function
End Function


</syntaxhighlight>
</lang>


Test:
Test:
Line 5,899: Line 5,899:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>fcn lzwCompress(uncompressed){ // text-->list of 12 bit ints
<syntaxhighlight lang="zkl">fcn lzwCompress(uncompressed){ // text-->list of 12 bit ints
dictionary:=(256).pump(Dictionary(),fcn(n){ return(n.toChar(),n) });
dictionary:=(256).pump(Dictionary(),fcn(n){ return(n.toChar(),n) });
w,compressed:="",List();
w,compressed:="",List();
Line 5,926: Line 5,926:
}
}
decommpressed.text
decommpressed.text
}</lang>
}</syntaxhighlight>
<lang zkl>compressed:=lzwCompress("TOBEORNOTTOBEORTOBEORNOT");
<syntaxhighlight lang="zkl">compressed:=lzwCompress("TOBEORNOTTOBEORTOBEORNOT");
compressed.toString(*).println();
compressed.toString(*).println();


lzwUncompress(compressed).println();</lang>
lzwUncompress(compressed).println();</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>