kerem.im
Günlük Notlar
Tüm kayıtlar
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.

İçindekiler
  1. Problem Statement
  2. Description
  3. Input Format
  4. Output Format
  5. Example
  6. Flowchart
  7. Solution

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 NN (N>0N > 0), immediately followed by a single character CC.
  • A negative integer −N-N (N>0N > 0), immediately followed by a sequence of NN 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 NN followed by character CC, print CC repeated NN times.
  • For a negative integer −N-N followed by NN characters, print those NN 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:

  1. 3a → Positive 3 means repeat 'a' 3 times (aaa).
  2. -4bcde → Negative 4 means read and print the next 4 literal characters (bcde).
  3. 2! → Positive 2 means repeat '!' 2 times (!!).
  4. 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| SN

Solution

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;
}
Kopyalandı!