-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlzw_compression.sf
80 lines (64 loc) · 1.75 KB
/
lzw_compression.sf
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
#!/usr/bin/ruby
# Implementation of the LZW compression algorithm.
# See also:
# https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch
# Compress a string to a list of output symbols.
func compress(String uncompressed) -> Array {
# Build the dictionary.
var dict_size = 256;
var dictionary = Hash.new;
0 .. dict_size-1 -> each { |i|
dictionary{i.chr} = i.chr;
};
var w = '';
var result = [];
uncompressed.each { |c|
var wc = w+c;
if (dictionary.has_key(wc)) {
w = wc;
} else {
result.append(dictionary{w});
# Add wc to the dictionary.
dictionary{wc} = dict_size;
dict_size++;
w = c;
}
};
# Output the code for w.
if (w != '') {
result.append(dictionary{w});
};
return result;
};
# Decompress a list of output ks to a string.
func decompress(Array compressed) -> String {
# Build the dictionary.
var dict_size = 256;
var dictionary = Hash.new;
0 .. dict_size-1 -> each { |i|
dictionary{i.chr} = i.chr;
};
var w = compressed.shift;
var result = w;
compressed.each { |k|
var entry;
if (dictionary.has_key(k)) {
entry = dictionary{k};
} elsif (k == dict_size) {
entry = w+w.substr(0,1);
} else {
die "Bad compressed k: #{k}";
};
result += entry;
# Add w+entry[0] to the dictionary.
dictionary{dict_size} = w+entry.substr(0,1);
dict_size++;
w = entry;
};
return result;
};
# How to use:
var compressed = compress('TOBEORNOTTOBEORTOBEORNOT');
say compressed.join(' ');
var decompressed = decompress(compressed);
say decompressed;