LZW compression: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 8: | Line 8: | ||
=={{header|11l}}== |
=={{header|11l}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<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))</ |
print(decompress(&compressed))</syntaxhighlight> |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
Line 57: | Line 57: | ||
lzw.ads: |
lzw.ads: |
||
< |
<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;</ |
end LZW;</syntaxhighlight> |
||
lzw.adb: |
lzw.adb: |
||
< |
<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;</ |
end LZW;</syntaxhighlight> |
||
test.adb: |
test.adb: |
||
< |
<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;</ |
end Test;</syntaxhighlight> |
||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<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</ |
print decompressed</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 274: | Line 274: | ||
=={{header|BaCon}}== |
=={{header|BaCon}}== |
||
< |
<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</ |
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. |
||
< |
<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$</ |
= 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.)''' |
||
< |
<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; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C sharp}}== |
=={{header|C sharp}}== |
||
{{trans|Java}} |
{{trans|Java}} |
||
< |
<syntaxhighlight lang="c sharp">using System; |
||
using System.Collections.Generic; |
using System.Collections.Generic; |
||
using System.Text; |
using System.Text; |
||
Line 762: | Line 762: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 770: | Line 770: | ||
=={{header|C++}}== |
=={{header|C++}}== |
||
{{trans|D}} |
{{trans|D}} |
||
< |
<syntaxhighlight lang="cpp">#include <string> |
||
#include <map> |
#include <map> |
||
Line 850: | Line 850: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<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")</ |
(compress "TOBEORNOTTOBEORTOBEORNOT")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
< |
<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. |
||
< |
<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). |
||
< |
<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)</ |
t)</syntaxhighlight> |
||
And the format used: |
And the format used: |
||
< |
<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"</ |
"TOBEORNOTTOBEORTOBEORNOT"</syntaxhighlight> |
||
=={{header|D}}== |
=={{header|D}}== |
||
===Simpler Version=== |
===Simpler Version=== |
||
< |
<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); |
||
}</ |
}</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. |
||
< |
<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; |
||
}</ |
}</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. |
||
< |
<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; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Input size: 206403 |
<pre>Input size: 206403 |
||
Line 1,446: | Line 1,446: | ||
=={{header|Dylan}}== |
=={{header|Dylan}}== |
||
< |
<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"))</ |
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}} |
||
< |
<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</ |
IO.inspect str == dec</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,661: | Line 1,661: | ||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<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).</ |
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}} |
||
< |
<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</ |
\ 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</ |
END PROGRAM MAIN</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<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</ |
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]). |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 2,464: | Line 2,464: | ||
} |
} |
||
fmt.Println(decompressed) |
fmt.Println(decompressed) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,472: | Line 2,472: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
< |
<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() |
||
}</ |
}</syntaxhighlight> |
||
Testing: |
Testing: |
||
< |
<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()</ |
Uncompressed: '$result'""".stripIndent()</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Plaintext: 'TOBEORNOTTOBEORTOBEORNOT' |
<pre>Plaintext: 'TOBEORNOTTOBEORTOBEORNOT' |
||
Line 2,525: | Line 2,525: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<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"</ |
"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: |
||
< |
<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 |
||
)</ |
)</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: |
||
< |
<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 |
||
)</ |
)</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+}} |
||
< |
<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); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} (Command Line direct output): |
{{out}} (Command Line direct output): |
||
< |
<syntaxhighlight lang="java5">[84, 79, 66, 69, 79, 82, 78, 79, 84, 256, 258, 260, 265, 259, 261, 263] |
||
TOBEORNOTTOBEORTOBEORNOT</ |
TOBEORNOTTOBEORTOBEORNOT</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
< |
<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);</ |
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. |
||
< |
<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}`);</ |
${decomp}`);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,902: | Line 2,902: | ||
{{ works with|jq|1.4}} |
{{ works with|jq|1.4}} |
||
{{trans|JavaScript}} |
{{trans|JavaScript}} |
||
< |
<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] |
||
;</ |
;</syntaxhighlight> |
||
'''Example''': |
'''Example''': |
||
< |
<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}} |
||
< |
<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</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,020: | Line 3,020: | ||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
{{trans|Java}} |
{{trans|Java}} |
||
< |
<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) |
||
}</ |
}</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 |
||
''''''''''''''''''''''''''''''''''''''''</ |
''''''''''''''''''''''''''''''''''''''''</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<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)</ |
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[%]</ |
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</ |
echo decompressed</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,663: | Line 3,663: | ||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
{{trans|Java}} |
{{trans|Java}} |
||
< |
<syntaxhighlight lang="objeck">use Collection; |
||
class LZW { |
class LZW { |
||
Line 3,766: | Line 3,766: | ||
"]"->PrintLine(); |
"]"->PrintLine(); |
||
} |
} |
||
}</ |
}</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: |
||
< |
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h> |
||
#import <stdio.h> |
#import <stdio.h> |
||
Line 3,862: | Line 3,862: | ||
} |
} |
||
@end</ |
@end</syntaxhighlight> |
||
Usage example: |
Usage example: |
||
< |
<syntaxhighlight lang="objc">NSString *text = @"TOBEORNOTTOBEORTOBEORNOT"; |
||
int main() |
int main() |
||
Line 3,886: | Line 3,886: | ||
} |
} |
||
return EXIT_SUCCESS; |
return EXIT_SUCCESS; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} (reformatted by hand): |
{{out}} (reformatted by hand): |
||
Line 3,896: | Line 3,896: | ||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<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) |
||
;;</ |
;;</syntaxhighlight> |
||
here is the interface: |
here is the interface: |
||
< |
<syntaxhighlight lang="ocaml">val compress : uncompressed:string -> int list |
||
val decompress : compressed:int list -> string list</ |
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. |
||
< |
<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) |
||
;;</ |
;;</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). |
||
< |
<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): |
||
< |
<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: |
||
< |
<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";</ |
print "$decompressed\n";</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,163: | Line 4,163: | ||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
{{trans|Lua}} |
{{trans|Lua}} |
||
<!--< |
<!--<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> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,230: | Line 4,230: | ||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
{{trans|JavaScript}} |
{{trans|JavaScript}} |
||
< |
<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}}== |
||
< |
<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].</ |
Diffs = [[delete=X,xPos=Xs.length,yPos=Ys.length]|Diffs1].</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,398: | Line 4,398: | ||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<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) ) ) ) ) ) )</ |
(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). |
||
< |
<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;</ |
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. |
||
< |
<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</ |
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: |
||
< |
<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)</ |
print (decompressed)</syntaxhighlight> |
||
Output: |
Output: |
||
Line 4,776: | Line 4,776: | ||
=={{header|Racket}}== |
=={{header|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 |
<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);</ |
say decompress(@compressed);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,902: | Line 4,902: | ||
===version 1=== |
===version 1=== |
||
{{trans|Java}} |
{{trans|Java}} |
||
< |
<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</ |
Return res</syntaxhighlight> |
||
'''Output:''' |
'''Output:''' |
||
<pre>str=TOBEORNOTTOBEORTOBEORNOT |
<pre>str=TOBEORNOTTOBEORTOBEORNOT |
||
Line 4,995: | Line 4,995: | ||
This REXX version can execute on '''ASCII''' or '''EBCDIC''' systems. |
This REXX version can execute on '''ASCII''' or '''EBCDIC''' systems. |
||
< |
<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 $</ |
end /*k*/; return $</syntaxhighlight> |
||
{{out|output|text= when using the default input:}} |
{{out|output|text= when using the default input:}} |
||
<pre> |
<pre> |
||
Line 5,028: | Line 5,028: | ||
=={{header|Ring}}== |
=={{header|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: |
||
< |
<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</ |
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. |
||
< |
<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); |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
Line 5,269: | Line 5,269: | ||
=={{header|Scala}}== |
=={{header|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}}== |
||
< |
<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)</ |
(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}}== |
||
< |
<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;</ |
end func;</syntaxhighlight> |
||
Output: |
Output: |
||
Line 5,493: | Line 5,493: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
{{trans|Perl}} |
{{trans|Perl}} |
||
< |
<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</ |
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}} |
||
< |
<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) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,643: | Line 5,643: | ||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<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</ |
if {$s eq [LZW::decode [LZW::encode $s]]} then {puts success} else {puts fail} ;# ==> success</syntaxhighlight> |
||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
{{trans|Kotlin}} |
{{trans|Kotlin}} |
||
< |
<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)</ |
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}}== |
||
< |
<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 |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="zkl">compressed:=lzwCompress("TOBEORNOTTOBEORTOBEORNOT"); |
||
compressed.toString(*).println(); |
compressed.toString(*).println(); |
||
lzwUncompress(compressed).println();</ |
lzwUncompress(compressed).println();</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |