Run Length Encoding
February 26, 2010
A book by Brian Kernighan and P. J. Plauger, Software Tools in Pascal, describes a pair of programs, called compress
and expand
, that provide run-length encoding of text files. The compress
program takes a text file as input and writes a (hopefully smaller) version of the text file as output; the expand
program inverts that operation. Compression is achieved by replacing runs of four or more of the same character with a three-character code consisting of a tilde, a letter A through Z indicating 1 through 26 repetitions, and the character to be repeated. Runs longer than 26 characters are replaced by multiple encodings, andany literal appearance of the tilde in the input is encoded as a run of length 1. For instance, the string ABBB~CDDDDDEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
is encoded as ABBB~A~C~ED~ZE~DE
.
Your task is to write programs that compress and expand a text file. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
[…] Praxis – Run Length Encoding By Remco Niemeijer In today’s Programming Praxis exercise we have to implement a run length encoding algorithm. The provided […]
My Haskell solution (see http://bonsaicode.wordpress.com/2010/02/26/programming-praxis-run-length-encoding/ for a version with comments):
My take on compress. I interpreted “any literal appearance of the tilde in the input is encoded as a run of length 1” as being a special case, so the output is different from Niemeijer’s version when there are several tildes in a row.
Full code with a quickcheck test: http://codepad.org/VakQUriW
Python, done using regular expressions.
Like domor, I separately encoded each ~ in the input.