log #004 · ·
Run-Length Decoder
Decoding a variation of Run-Length Encoding in C: positive counts repeat a character, negative counts print literal characters, 0 ends the stream.
Problem Statement
Description
Write a C program that decodes a compressed stream of characters using a variation of Run-Length Encoding (RLE). The program should continuously read integer commands followed by character data until a termination signal (0) is encountered.
Input Format
The input consists of a continuous sequence of pairs (with no separating whitespace between the integer and the characters that follow it):
- A positive integer (), immediately followed by a single character .
- A negative integer (), immediately followed by a sequence of characters.
- The integer 0, which indicates the end of the input.
Output Format
Print the decoded string to standard output according to the following rules:
- For a positive integer followed by character , print repeated times.
- For a negative integer followed by characters, print those characters verbatim (once each).
- Stop processing and exit when 0 is read (do not print anything for 0).
Example
Input: 3a-4bcde2!0
Output: aaabcde!!
Explanation:
3a→ Positive 3 means repeat'a'3 times (aaa).-4bcde→ Negative 4 means read and print the next 4 literal characters (bcde).2!→ Positive 2 means repeat'!'2 times (!!).0→ Terminates the program.
Flowchart
First let’s draw the flowchart.
| var | type | init |
|---|---|---|
num |
int | – |
let |
char | – |
i |
int | 0 |
k |
int | 0 |
flowchart TD
S(["START"]) --> SN[/"scan num"/]
SN --> K1{"num != 0 ?"}
K1 -->|FALSE| BR["break"]
BR --> R[/"RETURN 0"/]
K1 -->|TRUE| K2{"num > 0 ?"}
K2 -->|TRUE| SL1[/"SCAN let"/]
SL1 --> K3{"i < num ?"}
K3 -->|TRUE| PL1[/"PRINT let"/]
PL1 --> K3
K3 -->|FALSE| SN
K2 -->|FALSE| NEG["num = (-1) · num"]
NEG --> K4{"k < num ?"}
K4 -->|TRUE| SL2[/"SCAN let"/]
SL2 --> PL2[/"print let"/]
PL2 --> K4
K4 -->|FALSE| SNSolution
Solution I found:
#include <stdio.h>
int main(void) {
int num;
char let;
while (1) {
scanf("%d", &num);
if (num == 0) break;
if (num > 0) {
scanf("%c", &let);
for (int i = 0; i < num; i++) {
printf("%c", let);
}
} else {
num = -num;
for (int k = 0; k < num; k++) {
scanf("%c", &let);
printf("%c", let);
}
}
}
return 0;
}