LZW compression: Difference between revisions

D code converted to D2
m (→‎{{header|Java}}: WW Java 1.5, better syntax highlighting)
(D code converted to D2)
Line 671:
 
=={{header|D}}==
<lang d>import std.stdio: writefln;
D 1, with Phobos, from the Python version (the final writefln works only on 7-bit ASCII strings):
<lang d>import std.stdio: writefln;
 
/// Compress a string to a list of output symbols.
int[] compress(string uncompressed) {
//int builddictSize the= dictionary256;
int dict_size = 256;
int[string] dictionary;
forforeach (int i; i0 <.. dict_size; i++dictSize)
dictionary["" ~ cast(char)i] = i;
 
Line 690 ⟶ 687:
else {
result ~= dictionary[w];
// add dictionary[wc] to= the dictionarydictSize++;
dictionary[wc] = dict_size;
dict_size++;
w = "" ~ c;
}
}
 
// output the code for w
if (w.length)
result ~= dictionary[w];
Line 703 ⟶ 696:
}
 
 
/// Decompress a list of output ks to a string.
string decompress(int[] compressed) {
//int builddictSize the= dictionary256;
int dict_size = 256;
string[int] dictionary;
forforeach (int i; i0 <.. dict_size; i++dictSize)
dictionary[i] = "" ~ cast(char)i;
 
Line 718 ⟶ 708:
if (k in dictionary)
entry = dictionary[k];
else if (k == dict_sizedictSize)
entry = w ~ w[0];
else
Line 724 ⟶ 714:
result ~= entry;
 
//dictionary[dictSize++] add= w+ ~ entry[0] to the dictionary;
dictionary[dict_size] = w ~ entry[0];
dict_size++;
 
w = entry;
}
Line 735 ⟶ 722:
void main() {
auto compressed = compress("TOBEORNOTTOBEORTOBEORNOT");
writefln(compressed);
 
auto decompressed = decompress(compressed);
writeflnwriteln(compressed, "\n", decompressed);
}</lang>
Output:
The output:
<lang d>[84, 79, 66, 69, 79, 82, 78, 79, 84, 256, 258, 260, 265, 259, 261, 263]
TOBEORNOTTOBEORTOBEORNOT</lang>
 
Anonymous user