log #003 · ·
Basic Run-Length Encoding
Compressing a line of text with Run-Length Encoding in C, character by character: problem statement, flowchart and solution.
Problem Statement
Description
Write a program that reads a single line of text from standard input and compresses it using Run-Length Encoding (RLE). In this encoding scheme, consecutive identical characters are replaced by the count of their occurrences immediately followed by the character itself.
Input Format
- A single line of characters terminated by a newline (
\n). - The line may be empty (contain only a newline character).
Output Format
- Print the compressed string on a single line, where each group of consecutive repeating characters is formatted as
<count><character>(with no spaces between groups). - If the input line is empty, print nothing and terminate the program.
Constraints
- Do not use arrays or strings to store the entire input; process the input character-by-character as a stream.
- Single characters that do not repeat consecutively should still be preceded by a count of 1.
Flowchart
Okay, in order to solve this problem we will first draw the flowchart:
| var | type | init |
|---|---|---|
prev |
char | – |
cur |
char | – |
count |
integer | 1 |
flowchart TD
S(["Start"]) --> SP[/"scan prev"/]
SP --> K1{"prev == '#92;n' ?"}
K1 -->|True| R1[/"return 0"/]
K1 -->|False| SC[/"scan cur"/]
SC --> K2{"cur == '#92;n' ?"}
K2 -->|True| P1["print count and prev"]
P1 --> R2[/"return 0"/]
K2 -->|False| K3{"cur == prev ?"}
K3 -->|True| INC["count++"]
INC --> SC
K3 -->|False| P2["print count and prev"]
P2 --> AS["prev = cur"]
AS --> RST["count = 1"]
RST --> SCSolution in C
#include <stdio.h>
int main(void) {
char prev;
char cur;
int count = 1;
/* We defined three variables. The reason why we defined
prev and cur is that we have to compare two values.
We need to store the previous value in order to be able to compare.
Count, on the other hand, is crucial because for repeating letters,
we have to count how many of them there are. */
scanf("%c", &prev);
if (prev == '\n') return 0; // This was to prevent an edge case
while (1) {
scanf("%c", &cur);
if (cur == '\n') {
printf("%d%c", count, prev);
break;
// Trivial. This is the only break case for our loop.
}
if (cur == prev) {
count++;
// Note that we don't print anything until we scan a different character.
} else {
printf("%d%c", count, prev);
prev = cur;
count = 1;
/* I first forgot to set the count to 1; it resets after each
letter is printed. */
}
}
return 0;
}