RosettaCodeData/Task/Huffman-coding/D/huffman-coding.d

22 lines
799 B
D
Raw Permalink Normal View History

2015-02-20 00:35:01 -05:00
import std.stdio, std.algorithm, std.typecons, std.container, std.array;
2013-04-10 21:29:02 -07:00
2015-02-20 00:35:01 -05:00
auto encode(alias eq, R)(Group!(eq, R) sf) /*pure nothrow @safe*/ {
2013-04-10 21:29:02 -07:00
auto heap = sf.map!(s => tuple(s[1], [tuple(s[0], "")]))
.array.heapify!q{b < a};
while (heap.length > 1) {
auto lo = heap.front; heap.removeFront;
auto hi = heap.front; heap.removeFront;
2015-02-20 00:35:01 -05:00
lo[1].each!((ref pair) => pair[1] = '0' ~ pair[1]);
hi[1].each!((ref pair) => pair[1] = '1' ~ pair[1]);
2013-04-10 21:29:02 -07:00
heap.insert(tuple(lo[0] + hi[0], lo[1] ~ hi[1]));
}
2015-02-20 00:35:01 -05:00
return heap.front[1].schwartzSort!q{ tuple(a[1].length, a[0]) };
2013-04-10 21:29:02 -07:00
}
2015-02-20 00:35:01 -05:00
void main() /*@safe*/ {
immutable s = "this is an example for huffman encoding"d;
foreach (const p; s.dup.sort().group.encode)
2013-04-10 21:29:02 -07:00
writefln("'%s' %s", p[]);
}