1-6-string-compression Algorithm
The 1-6-string-compression Algorithm, also known as Run Length Encoding (RLE), is a simple form of lossless data compression that is mainly used for compressing sequences of repeated characters in strings. The main idea behind this algorithm is to replace consecutive identical characters (also called runs) with a single character followed by the count of repetitions. This algorithm is particularly effective when dealing with strings containing long sequences of the same character or binary data with long runs of 0s or 1s.
The basic implementation of the 1-6-string-compression Algorithm involves iterating through the input string and keeping track of the current character and its run length. When a different character is encountered or the end of the string is reached, the current character and its run length are appended to the compressed output. This can result in significant compression for strings with long runs of the same character. However, it is worth noting that this type of compression may not be as effective for strings with minimal or no repetition, and in some cases, the compressed output may even be longer than the original input due to the additional information needed to store the run length.
#include <iostream>
#include <string>
std::string compress(std::string str)
{
size_t original_length = str.length();
if (original_length < 2) {
return str;
}
std::string out{""};
int count = 1;
for( size_t i = 1; i < original_length; ++i ) {
if (str[i-1] == str[i]) {
++count;
} else {
out += str[i-1];
out += std::to_string(count);
count = 1;
}
if (out.length() >= original_length) {
return str;
}
}
out += str[original_length-1];
out += std::to_string(count);
if (out.length() >= original_length) {
return str;
}
return out;
}
int main()
{
std::string str, out;
std::cout << "Enter a string:\n";
std::cin >> str;
out = compress(str);
if (str.compare(out)) {
std::cout << str << " can be compressed to " << out << std::endl;
} else {
std::cout << str << " can not be compressed\n";
}
return 0;
}