Subject: | non-full dictionary leads to infinite loop |
use Algorithm::Huffman;
my $string = "I'm a little teapot, short and stdout";
my %char_counting;
foreach my $i (0..length($string)) {
$char_counting{substr($string,$i,1)}++ };
my $huff = Algorithm::Huffman->new(\%char_counting);
my $encode_hash = $huff->encode_hash;
my $decode_hash = $huff->decode_hash;
my $encoding = $huff->encode_bitstring($string);
print "Look at the encoding bitstring of '$string': $encoding\n";
print "The decoding of $encoding is '",
$huff->decode_bitstring($encoding), "'";
^D
Works fine, outputs:
Look at the encoding bitstring of 'I'm a little teapot, short and
stdout':
101011011010100001000100101100100011111011010000011110000001011110101110000100011001010000010101001110010001011100000000110011100000010100001111
The decoding of
101011011010100001000100101100100011111011010000011110000001011110101110000100011001010000010101001110010001011100000000110011100000010100001111
is 'I'm a little teapot, short and stdout'
However, changing the string to encode to Hello, which has a capital H
not in %char_counting, leads to a program that never returns:
use Algorithm::Huffman;
my $string = "I'm a little teapot, short and stdout";
my %char_counting;
foreach my $i (0..length($string)) {
$char_counting{substr($string,$i,1)}++ };
my $huff = Algorithm::Huffman->new(\%char_counting);
my $encode_hash = $huff->encode_hash;
my $decode_hash = $huff->decode_hash;
my $encoding = $huff->encode_bitstring("Hello");
print "Look at the encoding bitstring of '$string': $encoding\n";
print "The decoding of $encoding is '",
$huff->decode_bitstring($encoding), "'";
^C