Skip to content

Instantly share code, notes, and snippets.

@y-fedorov
Last active May 22, 2018 08:46
Show Gist options
  • Save y-fedorov/4ca9e155a48197f6245cb7d2ec6cac8b to your computer and use it in GitHub Desktop.
Save y-fedorov/4ca9e155a48197f6245cb7d2ec6cac8b to your computer and use it in GitHub Desktop.
Run-length encoding implementation Example
#include <vector>
#include <iostream>
#include <sstream>
std::string RLE(std::string data) {
std::stringstream ss;
auto size = data.size();
size_t sequenceCounter = 0;
for (size_t i = 0; i < size; i++) {
auto currentChar = data[i];
auto nextChar = data[i + 1];
if (currentChar != nextChar || i == size - 1) {
ss << sequenceCounter + 1 << currentChar;
sequenceCounter = 0;
continue;
}
sequenceCounter++;
}
return ss.str();
}
int main()
{
std::string data = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
std::string correctResult = "12W1B12W3B24W1B14W";
std::string result = RLE(data);
if (result != correctResult) {
std::cout << "Fail!" << std::endl;
return EXIT_FAILURE;
}
std::string dataB = "ABCABCABCDDDFFFFFF";
std::string correctResultB = "1A1B1C1A1B1C1A1B1C3D6F";
std::string resultB = RLE(dataB);
if (resultB != correctResultB) {
std::cout << "Fail!" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment