Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
13
Task/Huffman-coding/Raku/huffman-coding-1.raku
Normal file
13
Task/Huffman-coding/Raku/huffman-coding-1.raku
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
sub huffman (%frequencies) {
|
||||
my @queue = %frequencies.map({ [.value, .key] }).sort;
|
||||
while @queue > 1 {
|
||||
given @queue.splice(0, 2) -> ([$freq1, $node1], [$freq2, $node2]) {
|
||||
@queue = (|@queue, [$freq1 + $freq2, [$node1, $node2]]).sort;
|
||||
}
|
||||
}
|
||||
hash gather walk @queue[0][1], '';
|
||||
}
|
||||
|
||||
multi walk ($node, $prefix) { take $node => $prefix; }
|
||||
multi walk ([$node1, $node2], $prefix) { walk $node1, $prefix ~ '0';
|
||||
walk $node2, $prefix ~ '1'; }
|
||||
31
Task/Huffman-coding/Raku/huffman-coding-2.raku
Normal file
31
Task/Huffman-coding/Raku/huffman-coding-2.raku
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
sub huffman (%frequencies) {
|
||||
my @queue = %frequencies.map: { .value => (hash .key => '') };
|
||||
while @queue > 1 {
|
||||
@queue.=sort;
|
||||
my $x = @queue.shift;
|
||||
my $y = @queue.shift;
|
||||
@queue.push: ($x.key + $y.key) => hash $x.value.deepmap('0' ~ *),
|
||||
$y.value.deepmap('1' ~ *);
|
||||
}
|
||||
@queue[0].value;
|
||||
}
|
||||
|
||||
# Testing
|
||||
|
||||
for huffman 'this is an example for huffman encoding'.comb.Bag {
|
||||
say "'{.key}' : {.value}";
|
||||
}
|
||||
|
||||
# To demonstrate that the table can do a round trip:
|
||||
|
||||
say '';
|
||||
my $original = 'this is an example for huffman encoding';
|
||||
|
||||
my %encode-key = huffman $original.comb.Bag;
|
||||
my %decode-key = %encode-key.invert;
|
||||
my @codes = %decode-key.keys;
|
||||
|
||||
my $encoded = $original.subst: /./, { %encode-key{$_} }, :g;
|
||||
my $decoded = $encoded .subst: /@codes/, { %decode-key{$_} }, :g;
|
||||
|
||||
.say for $original, $encoded, $decoded;
|
||||
Loading…
Add table
Add a link
Reference in a new issue