Run Length Encoding (RLE) is a simple compression technique that replaces consecutive occurrences of the same character with a count of occurrences and the character itself. It's particularly effective for images with large areas of uniform color.
Let's take an example:
Original String: "AAABBBCCCDDDE"
Encoded String: "3A3B4C3D1E"
Here's how it works:
Here's a basic implementation of RLE in code:
def encode(text):
"""Encodes a string using RLE."""
encoded_text = ''
count = 1
for i in range(1, len(text)):
if text[i] == text[i - 1]:
count += 1
else:
encoded_text += str(count) + text[i - 1]
count = 1
encoded_text += str(count) + text[-1]
return encoded_text
def decode(encoded_text):
"""Decodes an RLE encoded string."""
decoded_text = ''
i = 0
while i < len(encoded_text):
count = ''
while encoded_text[i].isdigit():
count += encoded_text[i]
i += 1
decoded_text += int(count) * encoded_text[i]
i += 1
return decoded_text
# Example usage
text = "AAABBBCCCDDDE"
encoded_text = encode(text)
decoded_text = decode(encoded_text)
print(f"Original Text: {text}")
print(f"Encoded Text: {encoded_text}")
print(f"Decoded Text: {decoded_text}")
Run Length Encoding is a basic yet useful compression technique. It's ideal for data with repeating patterns and provides a simple yet effective way to reduce file size.