RosettaCodeData/Task/LZW-compression/D/lzw-compression-1.d

41 lines
1 KiB
D
Raw Permalink Normal View History

2013-04-10 21:29:02 -07:00
import std.stdio, std.array;
2014-04-02 16:56:35 +00:00
auto compress(in string original) pure nothrow {
2013-04-10 21:29:02 -07:00
int[string] dict;
2014-04-02 16:56:35 +00:00
foreach (immutable char c; char.min .. char.max + 1)
dict[[c]] = c;
2013-04-10 21:29:02 -07:00
string w;
int[] result;
2014-04-02 16:56:35 +00:00
foreach (immutable ch; original)
2013-04-10 21:29:02 -07:00
if (w ~ ch in dict)
w = w ~ ch;
else {
result ~= dict[w];
2014-04-02 16:56:35 +00:00
dict[w ~ ch] = dict.length;
2013-04-10 21:29:02 -07:00
w = [ch];
}
return w.empty ? result : (result ~ dict[w]);
}
2014-04-02 16:56:35 +00:00
auto decompress(in int[] compressed) pure nothrow {
auto dict = new string[char.max - char.min + 1];
foreach (immutable char c; char.min .. char.max + 1)
dict[c] = [c];
2013-04-10 21:29:02 -07:00
auto w = dict[compressed[0]];
auto result = w;
2014-04-02 16:56:35 +00:00
foreach (immutable k; compressed[1 .. $]) {
2013-04-10 21:29:02 -07:00
auto entry = (k < dict.length) ? dict[k] : w ~ w[0];
result ~= entry;
dict ~= w ~ entry[0];
w = entry;
}
return result;
}
void main() {
2014-04-02 16:56:35 +00:00
auto comp = "TOBEORNOTTOBEORTOBEORNOT".compress;
writeln(comp, "\n", comp.decompress);
2013-04-10 21:29:02 -07:00
}