Anonymous user
Huffman coding: Difference between revisions
→{{header|Perl 6}}: Clean up and modernize the original tree-building solution as well.
(→{{header|Perl 6}}: add solution that doesn't build a tree, and improve testing/demo section) |
(→{{header|Perl 6}}: Clean up and modernize the original tree-building solution as well.) |
||
Line 3,736:
===By building a tree===
{{works with|rakudo|2015-
<lang perl6>sub huffman (
my
given @queue.splice(0, 2) -> ([$freq1, $node1], [$freq2, $node2]) {
▲ while @q > 1 {
@queue = (|@queue, [$freq1 + $freq2, [$node1, $node2]]).sort;
}
}
multi walk (@node, $prefix) {▼
}
multi walk ($node, $prefix) { take $node => $prefix }</lang>▼
walk $node2, $prefix ~ '1'; }</lang>
===Without building a tree===
{{works with|rakudo|2015-12-17}}
<lang perl6>sub huffman (%frequencies
my @queue = %frequencies.map: { .value => (hash .key => '') };
while @queue > 1 {
Line 3,762 ⟶ 3,759:
my $x = @queue.shift;
my $y = @queue.shift;
@queue.push: ($x.key + $y.key) => hash $x.value.deepmap(
$y.value.deepmap(
}
@queue[0].value;
|