14281 - Polymorphic Run-Length Encoding Class   

Description

The task is to define the class ‘RleCodec’ for run-length encoding:

The rule of run-length encoding is simple: Count the number of consecutive repeated characters in a string, and replace the repeated characters by the count and a single instance of the character. For example, if the input string is ‘AAADDDDDDDBBGGGGGCEEEE’, its run-length encoding will be ‘3A7DBB5GC4E’, because there are three A’s, seven D’s, … etc. Note that we do not need to encode runs of length one or two, since ‘2B’ and ‘1C’ are not shorter than ‘BB’ and ‘C’.


Abstract base class ‘Codec

We first design the abstract base class ‘Codec’ as an interface, which contains two pure virtual functions encode() and decode()

class Codec {
public:
    Codec(std::string s): encoded{false}, code_str{s} { }
    virtual ~Codec() { } // virtual destructor; do nothing
    virtual void encode() = 0;
    virtual void decode() = 0;
    void show(std::ostream& os) const {
        os << code_str;
    }
    bool is_encoded() const { return encoded; }
protected:
    bool encoded;
    std::string code_str;
};

TODOs: In ‘function.cpp’, please

  1. define two concrete derived classes from the abstract base class ‘Codec’ by overriding the two pure virtual functions:
  • class DummyCodec: simply updating the coding status in encode() and decode() accordingly, and doing nothing else;
  • class RleCodec: for the run-length encoding explained above;
  1. implement the function getCodec(), which returns the address of a Codec object according to the parameter type, where the type of the Codec can be "Dummy" or "RLE".
Codec* getCodec(const std::string& type, const std::string& is);

For more information, you should refer to the main.cpp and function.h.


Note
It is highly recommended to practice std::stringstream in this problem. Here is a simple code that shows you how to use stringstream:

#include <iostream>
#include <sstream> // header file for stringstream
using namespace std;
int main(){
    string s;
    stringstream ss;
    getline(cin, s);
    ss << s;
    while(!ss.eof()){
        string t;
        getline(ss, t, ' ');
        cout << t << "\n";
    }
    return 0;
}
/*
- Sample Input
This is a sentence for testing this code.
- Sample Output
This
is
a
sentence
for
testing
this
code.
*/

For more information, please refer to this article.

Input

The input contains a single line that consists of several characters.

Output

There are four lines.

The first and second lines are dummy encoding and decoding.

The third and fourth lines are RLE encoding and decoding.

Each line is followed by a new line character.

Sample Input  Download

Sample Output  Download

Partial Judge Code

14281.cpp

Partial Judge Header

14281.h


Discuss