RosettaCodeData/Task/LZW-compression/Groovy/lzw-compression-1.groovy

38 lines
1 KiB
Groovy
Raw Permalink Normal View History

2014-04-02 16:56:35 +00:00
def compress = { text ->
2017-09-23 10:01:46 +02:00
def dictionary = (0..<256).inject([:]) { map, ch -> map."${(char)ch}" = ch; map }
2014-04-02 16:56:35 +00:00
def w = '', compressed = []
text.each { ch ->
def wc = "$w$ch"
if (dictionary[wc]) {
w = wc
} else {
compressed << dictionary[w]
2017-09-23 10:01:46 +02:00
dictionary[wc] = dictionary.size()
2014-04-02 16:56:35 +00:00
w = "$ch"
}
}
if (w) { compressed << dictionary[w] }
compressed
}
def decompress = { compressed ->
2017-09-23 10:01:46 +02:00
def dictionary = (0..<256).inject([:]) { map, ch -> map[ch] = "${(char)ch}"; map }
int dictSize = 128;
String w = "${(char)compressed[0]}"
2014-04-02 16:56:35 +00:00
StringBuffer result = new StringBuffer(w)
2017-09-23 10:01:46 +02:00
compressed.drop(1).each { k ->
2014-04-02 16:56:35 +00:00
String entry = dictionary[k]
if (!entry) {
if (k != dictionary.size()) throw new IllegalArgumentException("Bad compressed k $k")
entry = "$w${w[0]}"
}
result << entry
2017-09-23 10:01:46 +02:00
dictionary[dictionary.size()] = "$w${entry[0]}"
2014-04-02 16:56:35 +00:00
w = entry
}
2017-09-23 10:01:46 +02:00
2014-04-02 16:56:35 +00:00
result.toString()
}