Run-length encoding
how it works
The idea on aaabccdddd, as the watch page runs it.
A run is one letter, or the same letter several times in a row: aaab has runs aaa and b. Many texts have long runs, so write each run once: how many letters, then the letter. aaab becomes 3a1b. Making a text shorter like this is called compressing it. Read from the left. The first letter starts a run. Compare each next letter with the run's letter. The same, and the run grows. Different, and you write the run and start a new one. At the end, write the last run. This page counts comparisons, one for each letter after the first.
| text | code | characters |
|---|---|---|
| aaabccdddd | 3a1b2c4d | 8 |
| xyzxyzxyzx | 1x1y1z1x1y1z1x1y1z1x | 20 |
| zzzzzzzzzz | 10z | 3 |
step 1 of 11
The first letter, a, starts a run of 1.
what it remembers to know where it is
- run's letter
- a
- run so far
- 1
step 3 of 11
The next letter is a too, so the run grows to 3.
what it remembers to know where it is
- run's letter
- a
- run so far
- 3
step 4 of 11
The next letter, b, is not a. Write the run under its first letter: 3, then a. Then b starts a run of 1.
what it remembers to know where it is
- run's letter
- b
- run so far
- 1
step 5 of 11
The next letter, c, is not b. Write the run under its first letter: 1, then b. Then c starts a run of 1.
what it remembers to know where it is
- run's letter
- c
- run so far
- 1
step 7 of 11
The next letter, d, is not c. Write the run under its first letter: 2, then c. Then d starts a run of 1.
what it remembers to know where it is
- run's letter
- d
- run so far
- 1
step 10 of 11
The next letter is d too, so the run grows to 4.
what it remembers to know where it is
- run's letter
- d
- run so far
- 4
step 11 of 11
Done: write the last run, 4, then d. The code is 3a1b2c4d: 8 characters for 10 letters, so it is shorter.
what it remembers to know where it is
- run's letter
- not yet
- run so far
- not yet
Where it says not yet, nothing is held there at that moment.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- the first letter starts a run of 1Python lines 10 and 11
- for each next letter, hold it against the run's letterPython lines 12 and 13
- the same: the run grows by 1Python line 14
- different: write the run's length and letter, and start a run of the new letterPython lines 16, 17 and 18
- at the end, write the last run; what is written is the codePython lines 19 and 20
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
def run_length_encoding(text):
"""A text of small letters written as its runs, each as its length and letter.
Read from the left, each next letter is held against the run's letter. The
same, and the run grows; different, and the run is written and the letter
starts a new one. At the end the last run is written. Returns the code, so
aaab gives 3a1b.
"""
code = "" # nothing written yet
letter = text[0] # the first letter starts a run
length = 1 # of 1
for next_letter in text[1:]: # each next letter
if next_letter == letter: # held against the run's letter
length += 1 # the same: the run grows by 1
else:
code += str(length) + letter # different: write the run
letter = next_letter # and start a run of the new letter
length = 1
code += str(length) + letter # at the end, write the last run
return code # the code
how it scales
The plot counts the comparisons the method makes on a text of letters, measured from 10 letters to 100,000.
Each dotted line up is ten times the one below, and each line across is ten times the one before. A count that grows in step with climbs one line up for each line across. The comparisons do: 9 at 10 letters, 99,999 at 100,000. Question 1 in section 4 works out why.
letters compared, ten times more at each mark up
, how many letters the text has, ten times more at each mark to the right
- any text of letters, as every text of that length makes the same comparisons; one with no letter twice in a row, such as xyzx, writes the mostsolid where measured by running it; dashed where its formula carries it on to ten millionslope 1: ten times n, 10 times the work
| letters compared | time | |
|---|---|---|
| 1,000 | 999 | about 999 nanoseconds |
| 100,000 | 99,999 | about 100 microseconds |
| 10,000,000 | 9,999,999 | about 10 milliseconds |
The letters compared are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.
make these counts yourself
Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.
"""Count run-length encoding's comparisons yourself, as the plot on this page does.
Run it with Python 3.12 or later. For each n it prints the comparisons the
method makes on a text of n letters, x, y and z in turn, and the characters
its code has, up to n = 100,000. The counts are the same on any computer; only
the time differs.
"""
def run_length_encoding(text):
"""A text of small letters written as its runs, each as its length and letter.
Read from the left, each next letter is held against the run's letter. The
same, and the run grows; different, and the run is written and the letter
starts a new one. At the end the last run is written. Returns the code, so
aaab gives 3a1b.
"""
code = "" # nothing written yet
letter = text[0] # the first letter starts a run
length = 1 # of 1
for next_letter in text[1:]: # each next letter
if next_letter == letter: # held against the run's letter
length += 1 # the same: the run grows by 1
else:
code += str(length) + letter # different: write the run
letter = next_letter # and start a run of the new letter
length = 1
code += str(length) + letter # at the end, write the last run
return code # the code
def count(text):
"""The same method on text, counting each comparison it makes."""
comparisons = 0
letter = text[0]
for next_letter in text[1:]:
comparisons += 1 # held against the run's letter
if next_letter != letter:
letter = next_letter # a new run starts
return comparisons
if __name__ == "__main__":
print(f"{'n':>7} {'comparisons':>12} {'characters':>11}")
for n in (10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10_000, 20_000, 50_000, 100_000):
text = ("xyz" * (n // 3 + 1))[:n]
print(f"{n:>7} {count(text):>12} {len(run_length_encoding(text)):>11}")
best, worst and average
Best, worst and average usually name different inputs of one size. Here every text of letters makes the same comparisons, whatever its letters. So the table has one column, under the name worst. Its characters written are the most any text of letters writes: a text with no letter twice in a row, as question 2 shows.
A case is one kind of input. A bound says how fast its cost grows as grows.
The count is in the grid. Here it is , which stays between half of and from 2 up, so every bound is of : , and . Section 4 shows it.
| worstany text of letters, as every text of that length makes the same comparisons; one with no letter twice in a row, such as xyzx, writes the most | |
|---|---|
| letters compared | |
| characters written | at most ; exactly with no letter twice in a row |
| how the letters compared grow in each case | |
| tight, | |
| ceiling, | |
| floor, | |
extra memory: the run's letter and its length so far, and the code, at most characters
Extra memory is the room it needs on top of the input itself, while it runs.
| text | letters | comparisons | characters written |
|---|---|---|---|
| aa | 2 | 1 | 2 |
| ab | 2 | 1 | 4 |
| aaabccdddd | 10 | 9 | 8 |
| xyzxyzxyzx | 10 | 9 | 20 |
| zzzzzzzzzz | 10 | 9 | 3 |
where the formula comes from
Two questions, each worked line by line. Question 1 is the count the plot draws.
the move: one comparison each, after the first
the line:letter held against same comparisons so far a - - 0 a a yes 1 b a no 2 c b no 3 c c yes 4 c c yes 5 aabccc: the first a starts a run. Each of the other 5 letters is compared once, the same or not. why it is allowed: The first letter starts a run, with nothing to compare. Each other letter is held against the run's letter once, and the method never goes back. For aabccc, 5.
the move: a ceiling
the line:why it is allowed: By line 1, as is less than .
guess it, thenthe move: read the bound
the line:why it is allowed: By line 2, with the fixed multiple 1, from 1 letter on.
guess it, thenthe move: a floor
the line:half of n n - 1 n 1 1 2 2 3 4 3 5 6 5 9 10 From 2 letters up, is at least half of , and below . why it is allowed: By line 1. From 2 letters up, 1 is at most half of , so is at least less half of , which is half of . For 6, 5 is at least 3.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 4, with the fixed multiple a half, from 2 letters on.
guess it, thenthe move: both together
the line:why it is allowed: Lines 3 and 5 bound by the same growth.
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
the move: every run is one letter
the line:why it is allowed: The first letter starts a run. Each other letter differs from the one before, so it starts a new run, ended by the next letter or the end. xyzx has 4 runs.
the move: count them
the line:why it is allowed: By line 1, runs, and each writes 1, then its letter, 2 characters. For xyzx, 1x1y1z1x, 8.
guess it, thenthe move: a longer run
the line:run L writes characters b 1 1b 2 aaa 3 3a 2 zzzzzzzzzz 10 10z 3 A run of 1 writes twice its letters. Longer runs write fewer. why it is allowed: The method writes each run as its length, then its letter. aaa writes 3a, 2 characters; ten z's write 10z, 3, as 10 has two digits.
guess it, thenthe move: put the digits' limit into line 3
the line:L digits characters twice L 2 1 2 4 9 1 2 18 10 2 3 20 100 3 4 200 From 2 letters up, a run writes at most its letters, and far under twice them. why it is allowed: 2 to 9 have 1 digit, and 1 is at most less 1. 10 to 99 have 2 digits and are at least 10; 100 to 999 have 3 and are at least 100. Each extra digit makes the smallest 10 times bigger but adds only 1 digit. So from 2 up, the number has at most less 1 digits; line 3 adds 1 letter, so at most .
guess it, thenthe move: each run at most twice its letters
the line:run L writes twice L aa 2 2 4 b 1 2 2 ccc 3 2 6 total 6 6 12 aabccc, each run writes at most twice its letters, so the code, 6 characters, is at most twice the text, 12. why it is allowed: A run of 1 writes 2 by line 3. From 2 up, at most by line 4, under .
guess it, thenthe move: add up the runs
the line:why it is allowed: By line 5, and the runs' letters add up to , so the code has at most characters. Exactly only when every run is 1 letter, as by line 5 a longer run writes at most , under .
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
count it yourself
aabccc, step by step.
| step | what happens | letters compared | characters written |
|---|---|---|---|
| 1 | The first letter, a, starts a run of 1. | 0 | 0 |
| 2 | The next letter is a too, so the run grows to 2. | 1 | 0 |
| 3 | The next letter, b, is not a. Write the run under its first letter: 2, then a. Then b starts a run of 1. | 2 | 2 |
| 4 | The next letter, c, is not b. Write the run under its first letter: 1, then b. Then c starts a run of 1. | 3 | 4 |
| 5 | The next letter is c too, so the run grows to 2. | 4 | 4 |
| 6 | The next letter is c too, so the run grows to 3. | 5 | 4 |
| 7 | Done: write the last run, 3, then c. The code is 2a1b3c: 6 characters for 6 letters, the same length. | 5 | 6 |
In all, 5 letters compared. The formula from section 4, , gives at : the same.
where you meet it
Wherever long runs are common, as in drawings with large plain areas, a form of this method is used.
fax machines
A fax sends a page line by line. Each line is runs of white dots and black dots taking turns, white first, so it sends only the runs' lengths. Each length up to 63 has its own code; a longer one sends a code for its multiple of 64 first. Some codes are much shorter than others.
source: ITU-T Recommendation T.4, Standardization of Group 3 facsimile terminals for document transmission (opens in a new tab)
Windows bitmap files
A bitmap file may store its dots with RLE8. Two bytes, a count from 1 to 255 and a colour's number, stand for that many dots of that colour; a byte is a stored number from 0 to 255.
source: Microsoft's documentation, Bitmap Compression (opens in a new tab)
TIFF's PackBits
TIFF image files can use PackBits. A run of 2 to 128 equal bytes can be stored as 2 bytes: how many, then the byte. Bytes with no repeats are stored as they are, after one byte saying how many, up to 128 at a time.
source: Aldus Corporation's TIFF Revision 6.0 specification (opens in a new tab) (1992, now Adobe's), section 9, PackBits Compression
| dots | lengths sent |
|---|---|
| white 5, black 3, white 8 | 5, 3, 8 |
| black 2, white 14 | 0, 2, 14 |
what is used instead
In ordinary words a run is seldom longer than 2. So files of words use other methods: Huffman coding, which gives common letters short codes, or a method that finds whole stretches seen before. The books warn that data already compressed, such as a JPEG photograph, only grows when compressed again (volume three, chapter 36).
how it compares
Three ways to write a text. The two that write runs each make comparisons; keeping the text as it is makes none. They differ in what they write.
| way | aaabccdddd | xyzxyzxyzx | zzzzzzzzzz |
|---|---|---|---|
| the text as it is | 10 | 10 | 10 |
| every run as length and letter | 8 | 20 | 3 |
| a run of 1 as its letter alone | 7 | 10 | 3 |