<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Lossless data compression &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/lossless-data-compression/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>on web development</description>
	<lastBuildDate>Tue, 13 Feb 2018 08:18:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.0.3</generator>
	<item>
		<title>Computer Algorithms: Lossy Image Compression with Run-Length Encoding</title>
		<link>/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/</link>
		<comments>/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/#comments</comments>
		<pubDate>Thu, 03 May 2012 20:27:06 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Coding theory]]></category>
		<category><![CDATA[Data compression]]></category>
		<category><![CDATA[data compression algorithm]]></category>
		<category><![CDATA[Graphics file formats]]></category>
		<category><![CDATA[image compression]]></category>
		<category><![CDATA[Image processing]]></category>
		<category><![CDATA[Information theory]]></category>
		<category><![CDATA[jpeg]]></category>
		<category><![CDATA[Lossless data compression]]></category>
		<category><![CDATA[lossy algorithm]]></category>
		<category><![CDATA[Lossy compression]]></category>
		<category><![CDATA[PCX]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Pixel]]></category>
		<category><![CDATA[Run-length encoding]]></category>
		<category><![CDATA[suitable algorithm]]></category>
		<category><![CDATA[Technology/Internet]]></category>

		<guid isPermaLink="false">/?p=3078</guid>
		<description><![CDATA[Introduction Run-length encoding is a data compression algorithm that helps us encode large runs of repeating items by only sending one item from the run and a counter showing how many times this item is repeated. Unfortunately this technique is useless when trying to compress natural language texts, because they don’t have long runs of &#8230; <a href="/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Lossy Image Compression with Run-Length Encoding</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Run-length Encoding">Computer Algorithms: Data Compression with Run-length Encoding </a></li>
<li><a href="/2012/01/16/computer-algorithms-data-compression-with-bitmaps/" rel="bookmark" title="Computer Algorithms: Data Compression with Bitmaps">Computer Algorithms: Data Compression with Bitmaps </a></li>
<li><a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" rel="bookmark" title="Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution">Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution </a></li>
<li><a href="/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Relative Encoding">Computer Algorithms: Data Compression with Relative Encoding </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p><a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" title="Computer Algorithms: Data Compression with Run-length Encoding">Run-length encoding</a> is a data compression algorithm that helps us encode large runs of repeating items by only sending one item from the run and a counter showing how many times this item is repeated. Unfortunately this technique is useless when trying to compress natural language texts, because they don’t have long runs of repeating elements. In the other hand RLE is useful when it comes to image compression, because images happen to have long runs pixels with identical color. </p>
<p>As you can see on the following picture we can compress consecutive pixels by only replacing each run with one pixel from it and a counter showing how many items it contains.</p>
<figure id="attachment_3101" style="width: 619px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/1.LosslessRLEforImages.png"><img src="/wp-content/uploads/2012/05/1.LosslessRLEforImages.png" alt="Lossless RLE for Images" title="Lossless RLE for Images" width="619" height="216" class="size-full wp-image-3101" srcset="/wp-content/uploads/2012/05/1.LosslessRLEforImages.png 619w, /wp-content/uploads/2012/05/1.LosslessRLEforImages-300x104.png 300w" sizes="(max-width: 619px) 100vw, 619px" /></a><figcaption class="wp-caption-text">Although lossless RLE can be quite effective for image compression, it is still not the best approach!</figcaption></figure>
<p>In this case we can save only counters for pixels that are repeated more than once. Such the input stream “aaaabbaba” will be compressed as “[4]a[2]baba”. </p>
<p>Actually there are several ways run-length encoding can be used for image compression. A possible way of compressing a picture can be either row by row or column by column, as it is shown on the picture below.</p>
<p><figure id="attachment_3102" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/2.RowbyRowandColbyCol.png"><img src="/wp-content/uploads/2012/05/2.RowbyRowandColbyCol.png" alt="Row by row or column by column compression" title="Row by row or column by column compression" width="621" height="300" class="size-full wp-image-3102" srcset="/wp-content/uploads/2012/05/2.RowbyRowandColbyCol.png 621w, /wp-content/uploads/2012/05/2.RowbyRowandColbyCol-300x144.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">Row by row or column by column compression.</figcaption></figure><span id="more-3078"></span></p>
<p>The problem in practice is that sometimes compressing row by row may be effective, while in other cases the same approach is very ineffective. This is illustrated by the image below.</p>
<figure id="attachment_3103" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/3.EffectiveandIneffectiveCompression.png"><img src="/wp-content/uploads/2012/05/3.EffectiveandIneffectiveCompression.png" alt="Effective and Ineffective Compression" title="Effective and Ineffective Compression" width="621" height="328" class="size-full wp-image-3103" srcset="/wp-content/uploads/2012/05/3.EffectiveandIneffectiveCompression.png 621w, /wp-content/uploads/2012/05/3.EffectiveandIneffectiveCompression-300x158.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">Sometimes image compression may be done only after some preprocessing that can help us understand the best compression approach!</figcaption></figure>
<p>Obviously run-length encoding is a very good approach when compressing images, however when we talk about big images with millions of pixels it’s somehow natural to come with some lossy compression.</p>
<h2>Overview</h2>
<p>Lossy RLE is a very suitable algorithm when it comes to images, because in most of the cases large images do appear to have big spaces of identical pixel colors, i.e. when the half of the picture is the blue sky. By using lossy compression we can skip very short runs.</p>
<p>First we’ve to say how long will be the shortest run that we will keep in the compression. For instance if 3 is the shortest run, then runs of 2 consecutive elements will be skipped.</p>
<figure id="attachment_3104" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/4.LossessImageRow.png"><img src="/wp-content/uploads/2012/05/4.LossessImageRow.png" alt="Lossless Pixel Row" title="Lossless Pixel Row" width="621" height="173" class="size-full wp-image-3104" srcset="/wp-content/uploads/2012/05/4.LossessImageRow.png 621w, /wp-content/uploads/2012/05/4.LossessImageRow-300x83.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">Lossless compression of a pixel row in some cases can be very inefective!</figcaption></figure>
<p>Of course if we set the shortest run to be only one element long, this will make our compression completely lossless, which isn’t very effective. However when we talk about millions of pixels even runs of three or more elements are very short, so it’s up to the developer to decide how long will be the shortest run.</p>
<h3>Some Examples</h3>
<p>Let&#8217;s first define the shortest run that we will keep untouched to be at least three element long.</p>
<figure id="attachment_3105" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/5.LossyImageRow.png"><img src="/wp-content/uploads/2012/05/5.LossyImageRow.png" alt="Lossy Pixel Row" title="Lossy Pixel Row" width="620" height="273" class="size-full wp-image-3105" srcset="/wp-content/uploads/2012/05/5.LossyImageRow.png 620w, /wp-content/uploads/2012/05/5.LossyImageRow-300x132.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">We can lose some information that is invisbile to the eye.</figcaption></figure>
<p>The above image is compressed more effectively than the lossless pixel row from the previous picture.</p>
<p>The thing is how to merge short runs. For instance the following three runs have to be blended into one color run.</p>
<figure id="attachment_3106" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/6.BlendingShortRuns.png"><img src="/wp-content/uploads/2012/05/6.BlendingShortRuns.png" alt="Blending Short Runs" title="Blending Short Runs" width="620" height="199" class="size-full wp-image-3106" srcset="/wp-content/uploads/2012/05/6.BlendingShortRuns.png 620w, /wp-content/uploads/2012/05/6.BlendingShortRuns-300x96.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">We must chose how to blend short runs!</figcaption></figure>
<p>We can choose the middle color (option #1) or not, but this will always depend on the picture and it will be effective in some cases and ineffective in other.</p>
<h2>Implementation</h2>
<p>Implementing run-length encoding is easy in general. Here’s a simple <a href="/category/php/" title="PHP on stoimen.com">PHP</a> code that shows a lossy RLE.</p>
<pre lang="PHP">
/**
 * Compresses an input list of objects by losing some data using
 * run-length encoding
 * 
 * @param mixed $objectList
 * @param int $minLength
 */
function lossyRLE($objectList, $minLength)
{
	$len 		= is_string($objectList) 
			? strlen($objectList)		// string as an input stream
			: count($objectList);		// array as an input stream
	$j 		= 1;
	$compressed = array();				// compressed output
	
	for ($i = 0; $i < $len; $i++) {
		if (isset($objectList[$i+1]) &#038;&#038; $objectList[$i] == $objectList[$i+1]) {
			$j++;
		} else {
			$l = count($compressed);
			// This is where RLE is converted to a lossy algorithm!
			// In case the run is shorter than a predefined length the
			// algorithm will skip these elements and will stretch the last
			// saved run.
			// NOTE: this logic can be changed in order to take other
			// decisions depending on the goals.
			if ($j < $minLength &#038;&#038; $j < $l) {
				$compressed[$l-1]['count'] += $j;
			} else {
				$compressed[] = array('count' => $j, $objectList[$i]);
			}
			$j = 1;
		}
	}
	
	return $compressed;
}

$input = 'aaaabbaabbbbba';

// aaaaaaaabbbbbb
lossyRLE($input, 3);
</pre>
<p>The code above can be modified in order to work with more complex data. Let’s say we have a “pixel” abstraction as on the example above.</p>
<pre lang="PHP">
/**
 * Pixel abstraction
 */
class Pixel
{
	private $_color = null;
	
	public function __construct($color = '')
	{
		$this->_color = $color;
	}
	
	public function getColor() 
	{
		return $this->_color;
	}
}

/**
 * Inits the pixels array
 * 
 * @param array $pixels
 */
function init(array &$pixels = array())
{
	$colors = array('red', 'green', 'blue');
	
	for ($i = 0; $i < 100; $i++) {
		$pixels[] = new Pixel($colors[mt_rand(0, 2)]);
	}
}

/**
 * Compresses an input list of objects by losing some data using
 * run-length encoding
 * 
 * @param mixed $objectList
 * @param int $minLength
 */
function lossyRLE($objectList, $minLength)
{
	$len 		= is_string($objectList) 
			? strlen($objectList)		// string as an input stream
			: count($objectList);		// array as an input stream
	$j 		= 1;
	$compressed = array();				// compressed output
	
	for ($i = 0; $i < $len; $i++) {
		if (isset($objectList[$i+1]) &#038;&#038; $objectList[$i] == $objectList[$i+1]) {
			$j++;
		} else {
			$l = count($compressed);
			// This is where RLE is converted to a lossy algorithm!
			// In case the run is shorter than a predefined length the
			// algorithm will skip these elements and will stretch the last
			// saved run.
			// NOTE: this logic can be changed in order to take other
			// decisions depending on the goals.
			if ($j < $minLength &#038;&#038; $l > $j) {
				$compressed[$l-1]['count'] += $j;
			} else {
				$compressed[] = array('count' => $j, $objectList[$i]);
			}
			$j = 1;
		}
	}
	
	return $compressed;
}

$pixels = array();

// initializes the pixels array
init($pixels);

$compressed = lossyRLE($pixels, 3);

print_r($compressed);
</pre>
<h2>Complexity</h2>
<p>In general lossless RLE compelxity is linear &#8211; O(n) where n is the number of items from the input stream. Even with the small modification above the complexity remains linear. However we can modify the compression in a slightly different manner (in order to get the middle value from consecutive short runs). This will somehow affect the complexity of the algorithm, of course.</p>
<h2>Application</h2>
<p>Run-length encoding isn’t a very effective option when compressing texts, but for images where long runs of the identical pixels happen to occur it is quite useful. </p>
<figure id="attachment_3107" style="width: 622px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/7.LossyRLE.png"><img src="/wp-content/uploads/2012/05/7.LossyRLE.png" alt="Lossy RLE in Practice" title="Lossy RLE in Practice" width="622" height="483" class="size-full wp-image-3107" srcset="/wp-content/uploads/2012/05/7.LossyRLE.png 622w, /wp-content/uploads/2012/05/7.LossyRLE-300x232.png 300w" sizes="(max-width: 622px) 100vw, 622px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<p>Nevertheless RLE is easy to convert into a lossy algorithm, that makes it very suitable for image compression.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Run-length Encoding">Computer Algorithms: Data Compression with Run-length Encoding </a></li>
<li><a href="/2012/01/16/computer-algorithms-data-compression-with-bitmaps/" rel="bookmark" title="Computer Algorithms: Data Compression with Bitmaps">Computer Algorithms: Data Compression with Bitmaps </a></li>
<li><a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" rel="bookmark" title="Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution">Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution </a></li>
<li><a href="/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Relative Encoding">Computer Algorithms: Data Compression with Relative Encoding </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Data Compression with Relative Encoding</title>
		<link>/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/</link>
		<comments>/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/#comments</comments>
		<pubDate>Mon, 30 Jan 2012 18:27:26 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Africa]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Algorithmic efficiency]]></category>
		<category><![CDATA[Application This algorithm]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Data compression]]></category>
		<category><![CDATA[data compression algorithm]]></category>
		<category><![CDATA[Google Inc.]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Lossless data compression]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Run-length encoding]]></category>
		<category><![CDATA[San Francisco]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[web server]]></category>
		<category><![CDATA[west coast]]></category>
		<category><![CDATA[Yahoo! Communications Europe Ltd.]]></category>

		<guid isPermaLink="false">/?p=2658</guid>
		<description><![CDATA[Overview Relative encoding is another data compression algorithm. While run-length encoding, bitmap encoding and diagram and pattern substitution were trying to reduce repeating data, with relative encoding the goal is a bit different. Indeed run-length encoding was searching for long runs of repeating elements, while pattern substitution and bitmap encoding were trying to “map” where &#8230; <a href="/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Data Compression with Relative Encoding</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Run-length Encoding">Computer Algorithms: Data Compression with Run-length Encoding </a></li>
<li><a href="/2012/02/06/computer-algorithms-data-compression-with-prefix-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Prefix Encoding">Computer Algorithms: Data Compression with Prefix Encoding </a></li>
<li><a href="/2012/01/16/computer-algorithms-data-compression-with-bitmaps/" rel="bookmark" title="Computer Algorithms: Data Compression with Bitmaps">Computer Algorithms: Data Compression with Bitmaps </a></li>
<li><a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" rel="bookmark" title="Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution">Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Overview</h2>
<p>Relative encoding is another data compression algorithm. While <a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" title="Computer Algorithms: Data Compression with Run-length Encoding">run-length encoding</a>, <a href="/2012/01/16/computer-algorithms-data-compression-with-bitmaps/" title="Computer Algorithms: Data Compression with Bitmaps">bitmap encoding</a> and <a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" title="Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution">diagram and pattern substitution</a> were trying to reduce repeating data, with relative encoding the goal is a bit different. Indeed run-length encoding was searching for long runs of repeating elements, while pattern substitution and bitmap encoding were trying to “map” where the repetitions happen to occur. </p>
<p>The only problem with these algorithms is that not always the input stream of data is constructed out of repeating elements. It is clear that if the input stream contains many repeating elements there must be some way of reducing them. However that doesn’t mean that we cannot compress data if there are no repetitions. It all depends on the data. Let’s say we have the following stream to compress.</p>
<pre lang="PHP">
1, 2, 3, 4, 5, 6, 7
</pre>
<p>We can hardly imagine how this stream of data can be compressed. The same problem may occur when trying to compress the alphabet. Indeed the alphabet letters the very base of the words so it is the minimal part for word construction and it&#8217;s hard to compress them.</p>
<p>Fortunately this isn’t true always. An algorithm that tryies to deal with non repeating data is relative encoding. Let’s see the following input stream &#8211; years from a given decade (the 90&#8217;s).</p>
<pre lang="PHP">
1991,1991,1999,1998,1991,1993,1992,1992
</pre>
<p>Here we have 39 characters and we can reduce them. A natural approach is to remove the leading “19” as we humans often do.</p>
<pre lang="PHP">
91,91,99,98,91,93,92,92
</pre>
<p>Now we have a shorter string, but we can go even further with keeping only the first year. All other years will as relative to this year.</p>
<pre lang="PHP">
91,0,8,7,0,2,1,1
</pre>
<p>Now the volume of transferred data is reduced a lot (from 39 to 16 &#8211; more than 50%). However there are some questions we need to answer first, because the stream wont be always formatted in such pretty way. How about the next character stream?</p>
<pre lang="PHP">
91,94,95,95,98,100,101,102,105,110
</pre>
<p>We see that the value 100 is somehow in the middle of the interval and it is handy to use it as a base value for the relative encoding. Thus the stream above will become:</p>
<pre lang="PHP">
-9,-6,-5,-5,-2,100,1,2,5,10
</pre>
<p>The problem is that we can’t decide which value will be the <strong>base value</strong> so easily. What if the data was dispersed in a different way.</p>
<pre lang="PHP">
96,97,98,99,100,101,102,103,999,1000,1001,1002
</pre>
<p>Now the value of “100” isn’t useful, because compressing the stream will get something like this:</p>
<pre lang="PHP">
-4,-3,-2,-1,100,1,2,3,899,900,901,902
</pre>
<p>To group the relative values around “some” base values will be far more handy.</p>
<pre lang="PHP">
(-4,-3,-2,-1,100,1,2,3)(-1,1000,1,2)
</pre>
<p>However to decide which value will be the base value isn’t that easy. Also the encoding format is not so trivial. In the other hand this type of encoding can be useful in som specific cases as we can see bellow.<br />
<span id="more-2658"></span></p>
<h2>Implementation</h2>
<p>The implementation of this algorithm depends on the specific task and the format of the data stream. Assuming that we’ve to transfer the stream of years in JSON from a web server to a browser, here’s a short PHP snippet.</p>
<pre lang="PHP">
// JSON: [1991,1991,1999,1998,1999,1998,1995,1997,1994,1993]
$years = array(1991,1991,1999,1998,1999,1998,1995,1997,1994,1993);

function relative_encoding($input)
{
	$output = array();
	$inputLength = count($input);
	
	$base = $input[0];
	
	$output[] = $base;
	
	for ($i = 1; $i < $inputLength; $i++) {
		$output[] = $input[$i] - $base;
	}
	
	return $output;
}

// JSON: [1991,0,8,7,8,7,4,6,3,2]
echo json_encode(relative_encoding($years));
</pre>
<h2>Application</h2>
<p>This algorithm may be very useful in many cases, but here’s one of them. There are plenty of map applications around the web. Some products as <a href="http://maps.google.com/" title="Google Maps" target="_blank">Google Maps</a>, <a href="http://maps.yahoo.com/" title="Yahoo! Maps" target="_blank">Yahoo! Maps</a>, <a href="http://www.bing.com/maps/" title="Bing Maps" target="_blank">Bing Maps</a> are quite famous, while there are very useful open source projects as <a href="http://www.openstreetmap.org/" title="OpenStreetMap" target="_blank">OpenStreetMap</a>. The web sites using these apps are thousands. </p>
<p>A typical use case is to transfer lots of Geo coordinates from web server to a browser using JSON. Indeed any GEO point on Earth is relative to the point (0,0), which is located near the west coast of Africa, however on large zoom levels, when there are tons of markers we can transfer the information with relative encoding.</p>
<p>For instance the following diagram shows San Francisco with some markers on it. Their coordinates are be relative to the point (0,0) on Earth.</p>
<figure id="attachment_2682" style="width: 819px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/FullLatLononSanFrancisco.png"><img src="/wp-content/uploads/2012/01/FullLatLononSanFrancisco.png" alt="San Francisco map with full lat and lon markers" title="FullLatLononSanFrancisco" width="819" height="456" class="size-full wp-image-2682" srcset="/wp-content/uploads/2012/01/FullLatLononSanFrancisco.png 819w, /wp-content/uploads/2012/01/FullLatLononSanFrancisco-300x167.png 300w" sizes="(max-width: 819px) 100vw, 819px" /></a><figcaption class="wp-caption-text">Map markers can be relative to the (0, 0) point on Earth, which can be sometimes useless.</figcaption></figure>
<p>Far more useful may be to encode those markers, relative to the center of the city, thus we can save some space.</p>
<figure id="attachment_2681" style="width: 819px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/SanFranciscoMap.png"><img src="/wp-content/uploads/2012/01/SanFranciscoMap.png" alt="San Francisco map with relative encoded markers" title="SanFranciscoMap" width="819" height="456" class="size-full wp-image-2681" srcset="/wp-content/uploads/2012/01/SanFranciscoMap.png 819w, /wp-content/uploads/2012/01/SanFranciscoMap-300x167.png 300w" sizes="(max-width: 819px) 100vw, 819px" /></a><figcaption class="wp-caption-text">Relative encoding can be useful for map markers on large zoom level!</figcaption></figure>
<p>However this type of compression can be tricky, for example when dragging the map and updating the marker array. In the other hand we must group markers if we have to load more than one city. That’s why we must be careful when implementing it. But in the other hand it can be very useful - for instance on initial load of the map we can reduce data and speed up the load time. </p>
<p>The thing is that with relative encoding we can save only changes to base value (data) - something like version control systems and thus reducing data transfer and load. Here's a graphical example. In the first case on the diagram bellow we can see that each item is stored on its own. It doesn't depend on the adjacent items and it can be completely independent of them.</p>
<figure id="attachment_2694" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/chart_11.png"><img src="/wp-content/uploads/2012/01/chart_11.png" alt="Non-relative encoding" title="Non-relative encoding" width="600" height="371" class="size-full wp-image-2694" srcset="/wp-content/uploads/2012/01/chart_11.png 600w, /wp-content/uploads/2012/01/chart_11-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<p>However we can keep full info only for the first item and any other item will be relative to it, like on the diagram bellow.</p>
<figure id="attachment_2695" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/chart_21.png"><img src="/wp-content/uploads/2012/01/chart_21.png" alt="Relative encoding" title="Relative encoding" width="600" height="371" class="size-full wp-image-2695" srcset="/wp-content/uploads/2012/01/chart_21.png 600w, /wp-content/uploads/2012/01/chart_21-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Run-length Encoding">Computer Algorithms: Data Compression with Run-length Encoding </a></li>
<li><a href="/2012/02/06/computer-algorithms-data-compression-with-prefix-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Prefix Encoding">Computer Algorithms: Data Compression with Prefix Encoding </a></li>
<li><a href="/2012/01/16/computer-algorithms-data-compression-with-bitmaps/" rel="bookmark" title="Computer Algorithms: Data Compression with Bitmaps">Computer Algorithms: Data Compression with Bitmaps </a></li>
<li><a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" rel="bookmark" title="Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution">Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Data Compression with Bitmaps</title>
		<link>/2012/01/16/computer-algorithms-data-compression-with-bitmaps/</link>
		<comments>/2012/01/16/computer-algorithms-data-compression-with-bitmaps/#comments</comments>
		<pubDate>Mon, 16 Jan 2012 09:35:24 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[bitmap]]></category>
		<category><![CDATA[bitmap compressing algorithm]]></category>
		<category><![CDATA[Bzip2]]></category>
		<category><![CDATA[Coding theory]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Data compression]]></category>
		<category><![CDATA[gif]]></category>
		<category><![CDATA[Graphics file formats]]></category>
		<category><![CDATA[image compression]]></category>
		<category><![CDATA[Information theory]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Lossless data compression]]></category>
		<category><![CDATA[Run-length encoding]]></category>
		<category><![CDATA[Technology/Internet]]></category>

		<guid isPermaLink="false">/?p=2604</guid>
		<description><![CDATA[Overview In my previous post we saw how to compress data consisting of very long runs of repeating elements. This type of compression is known as &#8220;run-length encoding&#8221; and can be very handy when transferring data with no loss. The problem is that the data must follow a specific format. Thus the string “aaaaaaaabbbbbbbb” can &#8230; <a href="/2012/01/16/computer-algorithms-data-compression-with-bitmaps/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Data Compression with Bitmaps</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Relative Encoding">Computer Algorithms: Data Compression with Relative Encoding </a></li>
<li><a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Run-length Encoding">Computer Algorithms: Data Compression with Run-length Encoding </a></li>
<li><a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" rel="bookmark" title="Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution">Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution </a></li>
<li><a href="/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Lossy Image Compression with Run-Length Encoding">Computer Algorithms: Lossy Image Compression with Run-Length Encoding </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Overview</h2>
<p>In <a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" title="Computer Algorithms: Data Compression with Run-length Encoding">my previous post</a> we saw how to compress data consisting of very long runs of repeating elements. This type of compression is known as &#8220;run-length encoding&#8221; and can be very handy when transferring data with no loss. The problem is that the data must follow a specific format. Thus the string <strong>“aaaaaaaabbbbbbbb”</strong> can be compressed as <strong>“a8b8”</strong>. Now a string with length 16 can be compressed as a string with length 4, which is 25% of its initial length without loosing any information. There will be a problem in case the characters (elements) were dispersed in a different way. What would happen if the characters are the same, but they don’t form long runs? What if the string was <strong>“abababababababab”</strong>? The same length, the same characters, but we cannot use run-length encoding! Indeed using this algorithm we’ll get at best the same string.</p>
<p>In this case, however, we can see another fact. The string consists of too many repeating elements, although not arranged one after another. We can compress this string with a bitmap. This means that we can save the positions of the occurrences of a given element with a sequence of bits, which can be easily converted into a decimal value. In the example above the string <strong>“abababababababab”</strong> can be compressed as <strong>“1010101010101010”</strong>, which is <strong>43690</strong> in decimals, and even better <strong>AAAA</strong> in hexadecimal. Thus the long string can be compressed. When decompressing (decoding) the message we can convert again from decimal/hexadecimal into binary and match the occurrences of the characters. Well, the example above is too simple, but let’s say only one of the characters is repeating and the rest of the string consists of different characters like this: <strong>“abacadaeafagahai”</strong>. Then we can use bitmap only for the character “a” &#8211; <strong>“1010101010101010”</strong> and compress it as <strong>“AAAA bcdefghi”</strong>. As you can see all the example strings are exactly 16 characters and that is a limitation. To use bitmaps with variable length of the data is a bit tricky and it is not always easy (if possible) to decompress it.</p>
<p><figure id="attachment_2624" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/Run-lengthvs.BitmapCompression.png"><img src="/wp-content/uploads/2012/01/Run-lengthvs.BitmapCompression.png" alt="Bitmap Compression" title="Bitmap Compression" width="620" class="size-full wp-image-2624" srcset="/wp-content/uploads/2012/01/Run-lengthvs.BitmapCompression.png 1140w, /wp-content/uploads/2012/01/Run-lengthvs.BitmapCompression-300x160.png 300w, /wp-content/uploads/2012/01/Run-lengthvs.BitmapCompression-1024x547.png 1024w" sizes="(max-width: 1140px) 100vw, 1140px" /></a><figcaption class="wp-caption-text">Basically bitmap compression saves the positions of an element that is repeated very often in the message!</figcaption></figure><br />
<span id="more-2604"></span><br />
In the other hand bitmap compression  is not only applicable on strings. We can compress also arrays, objects or any kind of data. The example from my previous post is very suitable. Then we had to transfer a large array from a server to the client (browser) using <a href="/tag/json/" title="JSON on stoimen.com/blog">JSON</a>. The data then was very suitable for “run-length encoding”. Now let’s assume we have the same data &#8211; a set of different years, which this time are dispersed in a different way. </p>
<pre lang="PHP">
$data = array(
	0 	=> 1991,
	1 	=> 1992,
	2 	=> 1993,
	3 	=> 1994,
	4 	=> 1991,
	5 	=> 1992,
	6 	=> 1993,
	7 	=> 1992,
	8 	=> 1991,
	9 	=> 1991,
	10 	=> 1991,
	11 	=> 1992,
	12 	=> 1992,
	13 	=> 1991,
	14 	=> 1991,
	15 	=> 1992,	
	...
);
</pre>
<p>The JSON will encoded message will be the following (a simple but yet very large javascript array).</p>
<pre lang="PHP">
[1991,1992,1993,1994,1991,1992,1993,1992,1991,1991,1991,1992,1992,1991,1991,1992, ...]
</pre>
<p>However if we use bitmap compression we’ll get a &#8220;shorter&#8221; array.</p>
<pre lang="PHP">
$data = array(
	0 => array(1991, '1000100011100110'),
	1 => array(1992, '0100010100011001'),
	2 => array(1993, '0010001000000000'),
	3 => array(1994, '0001000000000000'),
);
</pre>
<p>Now the JSON is:</p>
<pre lang="PHP">
[[1991,"1000100011100110"],[1992,"0100010100011001"],[1993,"0010001000000000"],[1994,"0001000000000000"]]
</pre>
<p>It is obvious that the compression ratio is getting better and better as the uncompressed data grows. In fact, most of us know bitmap compression from images, because this algorithm is largely used for image compression. We can imagine how successful it can be when compressing black and white images (as black and white can be represented as 0 and 1s). Actually it is used for more than two colors (256 for instance) and again the level of compression is very high.</p>
<h2>Implementation</h2>
<p>The following implementation on <a href="/category/php/" title="PHP on stoimen.com">PHP</a> aims only to illustrate the bitmap compressing algorithm. As we know this algorithm can be applicable for any kind of data structures. </p>
<pre lang="PHP">
// too many repeating "a" characters
$msg = 'aazahalavaatalawacamaahakafaaaqaaaiauaacaaxaauaxaaaaaapaayatagaaoafaawayazavaaaazaaabararaaaaakakaaqaarazacajaazavanazaaaeanaaoajauaaaaaxalaraaapabataaavaaab';

function bitmap($message) 
{
	$i = 0;
	$bits = $rest = '';
	
	while ($v = $message[$i]) {
		if ($v == 'a') {
			$bits .= '1';
		} else {
			$bits .= '0';
			$rest .= $v;
		}
		$i++;
	}
	
	return number_format(bindec($bits), 0, '.', '') . $rest;;
}

echo bitmap($msg);

// uncompressed: 
acaaaaadaaaabalaaeaaaaganaaxakaavawamaasavajawaaaayaauaaadalanagaeaeamaarafalaazaaaiasaanaahaaazaraxaalaahaaawaaajasamahaajaakarapanaakaoakaanawalaacamauaamaal
// compressed:
152299251941730035874325065523548237677352452096zhlvtlwcmhkfqiucxuxpytgofwyzvzbrrkkqrzcjzvnzenojuxlrpbtvb
</pre>
<h2>Application</h2>
<p>This algorithm is very useful when there is an element in our data that repeats very often, so you need to investigate the nature of the data you want to compress. Actually because of this fact this algorithm is used for image compression as <a href="http://en.wikipedia.org/wiki/Portable_Network_Graphics" title="Portable Network Graphics" target="_blank">PNG8</a> or <a href="http://en.wikipedia.org/wiki/Graphics_Interchange_Format" title="Graphics Interchange Format" target="_blank">GIF</a>.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Relative Encoding">Computer Algorithms: Data Compression with Relative Encoding </a></li>
<li><a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Run-length Encoding">Computer Algorithms: Data Compression with Run-length Encoding </a></li>
<li><a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" rel="bookmark" title="Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution">Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution </a></li>
<li><a href="/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Lossy Image Compression with Run-Length Encoding">Computer Algorithms: Lossy Image Compression with Run-Length Encoding </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/01/16/computer-algorithms-data-compression-with-bitmaps/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Data Compression with Run-length Encoding</title>
		<link>/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/</link>
		<comments>/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/#comments</comments>
		<pubDate>Mon, 09 Jan 2012 09:08:06 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[Algorithmic efficiency]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[Bzip2]]></category>
		<category><![CDATA[Data compression]]></category>
		<category><![CDATA[data compression algorithm]]></category>
		<category><![CDATA[data compression algorithms]]></category>
		<category><![CDATA[faster services]]></category>
		<category><![CDATA[Google Inc.]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Lossless data compression]]></category>
		<category><![CDATA[lossless data compression algorithm]]></category>
		<category><![CDATA[Lossy compression]]></category>
		<category><![CDATA[programmer]]></category>
		<category><![CDATA[run-length algorithm]]></category>
		<category><![CDATA[Run-length encoding]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[This algorithm]]></category>
		<category><![CDATA[virtual machine]]></category>
		<category><![CDATA[web server]]></category>

		<guid isPermaLink="false">/?p=2594</guid>
		<description><![CDATA[Introduction No matter how fast today&#8217;s computers and networks are, the users will constantly need faster and faster services. To reduce the volume of the transferred data we usually use some sort of compression. That is why this computer sciences area will be always interesting to research and develop. There are many data compression algorithms, &#8230; <a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Data Compression with Run-length Encoding</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Lossy Image Compression with Run-Length Encoding">Computer Algorithms: Lossy Image Compression with Run-Length Encoding </a></li>
<li><a href="/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Relative Encoding">Computer Algorithms: Data Compression with Relative Encoding </a></li>
<li><a href="/2012/01/16/computer-algorithms-data-compression-with-bitmaps/" rel="bookmark" title="Computer Algorithms: Data Compression with Bitmaps">Computer Algorithms: Data Compression with Bitmaps </a></li>
<li><a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" rel="bookmark" title="Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution">Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>No matter how fast today&#8217;s computers and networks are, the users will constantly need faster and faster services. To reduce the volume of the transferred data we usually use some sort of compression. That is why this computer sciences area will be always interesting to research and develop.</p>
<p>There are many data compression algorithms, some of them lossless, others lossy, but their main goal aways will be to spare storage space and traffic. These algorithms are very useful when talking about data transfer between two distant places. Perhaps the best example is the transfer between a web server and a browser.</p>
<p>In the last few years a lot of research has been done on compressing files, executed on the client side. Such files are javascript, css, htmls and images. In fact servers and clients already have some techniques to compress data, like using <a href="http://www.gzip.org/" title="The gzip home page" target="_blank">GZIP</a> for instance, that can dramatically decrease the transfer. In the other hand there are lots of tools and tricks in order to decrease the size of the data.</p>
<p>Actually when a file is executed by the client&#8217;s virtual machine, it doesn&#8217;t matter how &#8220;beautifully&#8221; it is formatted from a programmer&#8217;s point of view. Thus the spaces, tabs and the new lines don&#8217;t bring any significant information for the environment. That is why such compressing tools like <a href="http://developer.yahoo.com/yui/compressor/" title="YUI Compressor" target="_blank">YUI Compressor</a>, <a href="http://code.google.com/closure/compiler/" title="Closure Compiler - Google Code" target="_blank">Google Closure Compiler</a>, etc. remove those symbols. Well, they can achieve even more in order to improve the compression rate. In this post I won&#8217;t cover this, but this shows how important data compression algorithms are.</p>
<p>It would be great if we could just compress data with some tool. Unfortunately this is not the case and usually the compression rate depends on the data itself. It is obvious that the choice of data compression algorithm depends mainly on the data and first of all we must explore the data.</p>
<p>Here I&#8217;ll cover one very simple lossless data compression algorithm called &#8220;run-length encoding&#8221; that can be very useful in some cases.</p>
<figure id="attachment_2618" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/Run-lengthEncoding1.png"><img src="/wp-content/uploads/2012/01/Run-lengthEncoding1.png" alt="Run-length Encoding" title="Run-length Encoding" width="620" class="size-full wp-image-2618" srcset="/wp-content/uploads/2012/01/Run-lengthEncoding1.png 978w, /wp-content/uploads/2012/01/Run-lengthEncoding1-300x129.png 300w" sizes="(max-width: 978px) 100vw, 978px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<h2>Overview</h2>
<p>This algorithm consists of replacing large sequences of repeating data with only one item of this data followed by a counter showing how many times this item is repeated. To become clearer let’s see a string example.</p>
<pre lang="PHP">
aaaaaaaaaabbbaxxxxyyyzyx
</pre>
<p>This string&#8217;s length is <strong>24</strong> and as we can see there are lots of repetitions. Using the run-length algorithm, we replace any run with shorter string followed by a counter.</p>
<pre lang="PHP">
a10b3a1x4y3z1y1x1
</pre>
<p>The length of this string is <strong>17</strong>, which is approximately <strong>70%</strong> of the initial length. <span id="more-2594"></span>Obviously this is not the optimal way to compress the given string. For instance we don&#8217;t need to use the digit “1” when the character is repeated only once. In some cases this approach can increase the length of the initial string which is exactly the opposite of what we need. In this case we’ll get the string bellow.</p>
<pre lang="PHP">
a10b3ax4y3zyx
</pre>
<p>Now the length of the resulting string is <strong>13</strong>, which is <strong>54%</strong> of the initial length! A variation of the example above is not to keep a counter of the repetitions of the character, but their position instead. Thus the initial string will be compressed as follows.</p>
<pre lang="PHP">
a0b10a13x14y18z21y22x23
</pre>
<p>Which of these two approaches you&#8217;ll use depends on the goal. In the second case we can achieve a good optimization of <a href="/2011/12/26/computer-algorithms-binary-search/" title="Computer Algorithms: Binary Search">binary search</a>.</p>
<p>It is clear that this algorithm is not only applicable on strings. We can achieve very good results on arrays. A typical example is the transfer of <a href="http://www.json.org/" title="JSON" target="_blank">JSON</a> from a server to a client. Then if there are large sequences of repeating data we can achieve great results.</p>
<h2>Implementation</h2>
<p>The implementation bellow is assuming that we&#8217;re compressing a string and it&#8217;s written on PHP. However the nature of this algorithm doesn&#8217;t restrict us to use only strings. As I said before with slight modifications we can use it with other data structures. It is important only to understand that the run-length algorithm is very useful on large sequences of repeating elements, no matter characters or array items.</p>
<pre lang="PHP">
$message = 'aaaaaaaaaabbbaxxxxyyyzyx';

function run_length_encode($msg)
{
	$i = $j = 0;
	$prev = '';
	$output = '';
	
	while ($msg[$i]) {
		if ($msg[$i] != $prev) {
			
			if ($i) 
				$output .= $j;
				
			$output .= $msg[$i];
				
			$prev = $msg[$i];
			
			$j = 0;
		}
		$j++;
		$i++;
	}
	
	$output .= $j;
	
	return $output;
}

// a10b3a1x4y3z1y1x1
echo run_length_encode($message);
</pre>
<p>And slightly optimized.</p>
<pre lang="PHP">
$message = 'aaaaaaaaaabbbaxxxxyyyzyx';

function run_length_encode($msg)
{
	$i = $j = 0;
	$prev = '';
	$output = '';
	
	while ($msg[$i]) {
		if ($msg[$i] != $prev) {
			
			if ($i && $j > 1) 
				$output .= $j;
				
			$output .= $msg[$i];
				
			$prev = $msg[$i];
			
			$j = 0;
		}
		$j++;
		$i++;
	}
	
	if ($j > 1)
		$output .= $j;
	
	return $output;
}

// a10b3ax4y3zyx
echo run_length_encode($message);
</pre>
<p>Finally a small change &#8211; now we store the position of the character.</p>
<pre lang="PHP">
$message = 'aaaaaaaaaabbbaxxxxyyyzyx';

function run_length_encode($msg)
{
	$i = 0;
	$prev = '';
	$output = '';
	
	while ($msg[$i]) {
		if ($msg[$i] != $prev) {
				
			$output .= $msg[$i] . $i;
				
			$prev = $msg[$i];
			
		}

		$i++;
	}
	
	return $output;
}

// a0b10a13x14y18z21y22x23
echo run_length_encode($message);
</pre>
<h2>Complexity and Data Compression</h2>
<p>We&#8217;re used to talk about complexity of an algorithm measuring time and we usually try to find the fastest implementation, like in search algorithms. Here it is not so important to compress data quickly, but to compress as much as possible so the output is as small as possible without lossing data. A great feature of run-length encoding is that this algorithm is easy to implement.</p>
<h2>Application</h2>
<p>We can use run-length encoding in many cases. It is commonly used to compress images and is very successful when we deal only with black and white images. Here I&#8217;ll cover another use case that I only mentioned above. Let&#8217;s say we have to transfer a very large array of data to our AJAX-powered application using JSON. Let&#8217;s say also that the data are some years, for instance the years of the premiere of a movie. There are lots of movies with a premiere in the same year, thus although the data is sorted, we actually can&#8217;t have any benefit. More important is that we have large sequences of data. Here we can use run-length encoding.</p>
<pre lang="PHP">
$data = array(
	0 	=> 1991,
	1 	=> 1991,
	...
	2223 	=> 1991,
	2224 	=> 1992,
	...
	19298 	=> 1995,
	19299 	=> 1996,
	...
);
</pre>
<p>As you can see to transfer the whole array can be a nightmare, especially on slow networks. It is better to compress it (i.e. with PHP&#8217;s <a href="http://php.net/manual/en/function.json-encode.php" title="PHP: json_encode" target="_blank">json_encode</a>).</p>
<pre lang="PHP">
// {"0":1991,"1":1991, ..., "2223":1991,"2224":1992, ..., "19298":1995,"19299":1996, ...}
echo json_encode($data);
</pre>
<p>After running run-length encoding we can receive something like the following array (note that these are only sample data and it&#8217;s up to you to decide which is the best format to store data).</p>
<pre lang="PHP">
$data = array(
	0 => array(1991, 2224),
	1 => array(1992, 3948),
	2 => array(1995, 2398),
	3 => array(1996, 3489),
);
</pre>
<p>And the JSON output.</p>
<pre lang="PHP">
// [[1991,2224],[1992,3948],[1995,2398],[1996,3489]]
echo json_encode($data);
</pre>
<p>Note that if the data is sorted we can achieve great success compressing it!!! This approach can be used for images, graphics or map coordinates.</p>
<p>This is only one example of how data compression can be useful in our daily work. Although the communication between the server and the client can be optimized and compressed, we can improve it. In other words we&#8217;re not always sure that the opposite side supports compression.</p>
<p>Well, it&#8217;s true that the client has to decompress the data, which can also be slow. Now in the first case we have only the time to transfer, as on the diagram bellow.</p>
<figure id="attachment_2609" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/DataTransferWithoutCompression.png"><img src="/wp-content/uploads/2012/01/DataTransferWithoutCompression.png" alt="Data Transfer Without Compression" title="Data Transfer Without Compression" width="620" class="size-full wp-image-2609" srcset="/wp-content/uploads/2012/01/DataTransferWithoutCompression.png 957w, /wp-content/uploads/2012/01/DataTransferWithoutCompression-300x54.png 300w" sizes="(max-width: 957px) 100vw, 957px" /></a><figcaption class="wp-caption-text">Time to transfer data without compression!</figcaption></figure>
<p>In the second case, we should sum the time for compression, transfer and decompression.</p>
<figure id="attachment_2610" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/DataTransferwithCompression.png"><img src="/wp-content/uploads/2012/01/DataTransferwithCompression.png" alt="Data Transfer with Compression" title="Data Transfer with Compression" width="620" class="size-full wp-image-2610" srcset="/wp-content/uploads/2012/01/DataTransferwithCompression.png 953w, /wp-content/uploads/2012/01/DataTransferwithCompression-300x59.png 300w" sizes="(max-width: 953px) 100vw, 953px" /></a><figcaption class="wp-caption-text">Time to send data with compression!</figcaption></figure>
<p>All this is important, but in general data compression can be handy in many cases in our daily work. </p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Lossy Image Compression with Run-Length Encoding">Computer Algorithms: Lossy Image Compression with Run-Length Encoding </a></li>
<li><a href="/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Relative Encoding">Computer Algorithms: Data Compression with Relative Encoding </a></li>
<li><a href="/2012/01/16/computer-algorithms-data-compression-with-bitmaps/" rel="bookmark" title="Computer Algorithms: Data Compression with Bitmaps">Computer Algorithms: Data Compression with Bitmaps </a></li>
<li><a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" rel="bookmark" title="Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution">Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
	</channel>
</rss>
