-
Notifications
You must be signed in to change notification settings - Fork 33
/
lzw_encoding.pl
executable file
·96 lines (71 loc) · 1.92 KB
/
lzw_encoding.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#!/usr/bin/perl
use 5.020;
use strict;
use warnings;
use constant DICT_SIZE => 256;
use experimental qw(signatures);
binmode(STDOUT, ':utf8');
sub create_dictionary() {
my %dictionary;
foreach my $i (0 .. DICT_SIZE - 1) {
$dictionary{chr $i} = chr $i;
}
return %dictionary;
}
sub compress ($uncompressed) {
my $dict_size = DICT_SIZE;
my %dictionary = create_dictionary();
my $w = '';
my @compressed;
foreach my $c (split(//, $uncompressed)) {
my $wc = $w . $c;
if (exists $dictionary{$wc}) {
$w = $wc;
}
else {
push @compressed, $dictionary{$w};
$dictionary{$wc} = chr($dict_size++);
$w = $c;
}
}
if ($w ne '') {
push @compressed, $dictionary{$w};
}
return @compressed;
}
sub decompress (@compressed) {
my $dict_size = DICT_SIZE;
my %dictionary = create_dictionary();
my $w = shift(@compressed);
my $result = $w;
foreach my $k (@compressed) {
my $entry = do {
if (exists $dictionary{$k}) {
$dictionary{$k};
}
elsif ($k eq chr($dict_size)) {
$w . substr($w, 0, 1);
}
else {
die "Invalid compression: $k";
}
};
$result .= $entry;
$dictionary{chr($dict_size++)} = $w . substr($entry, 0, 1);
$w = $entry;
}
return $result;
}
my $orig = 'TOBEORNOTTOBEORTOBEORNOT';
my @compressed = compress($orig);
my $enc = join('', @compressed);
my $dec = decompress(@compressed);
say "Encoded: $enc";
say "Decoded: $dec";
say '-' x 33;
if ($dec ne $orig) {
die "Decompression failed!";
}
printf("Original size : %s\n", length($orig));
printf("Compressed size : %s\n", length($enc));
printf("Compression ratio : %.2f%%\n", (length($orig) - length($enc)) / length($orig) * 100);