<?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>Computer science &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/computer-science/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: How to Determine the Day of the Week</title>
		<link>/2012/04/24/computer-algorithms-how-to-determine-the-day-of-the-week/</link>
		<comments>/2012/04/24/computer-algorithms-how-to-determine-the-day-of-the-week/#comments</comments>
		<pubDate>Tue, 24 Apr 2012 19:31:03 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Calculating the day of the week]]></category>
		<category><![CDATA[Calendars]]></category>
		<category><![CDATA[Chronology]]></category>
		<category><![CDATA[computer]]></category>
		<category><![CDATA[Computer science]]></category>
		<category><![CDATA[Doomsday rule]]></category>
		<category><![CDATA[February]]></category>
		<category><![CDATA[Gregorian calendar]]></category>
		<category><![CDATA[informatics]]></category>
		<category><![CDATA[Julian calendar]]></category>
		<category><![CDATA[Leap year]]></category>
		<category><![CDATA[month]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Units of time]]></category>
		<category><![CDATA[USD]]></category>
		<category><![CDATA[Year zero]]></category>

		<guid isPermaLink="false">/?p=3058</guid>
		<description><![CDATA[Introduction Do you know what day of the week was the day you were born? Monday or maybe Saturday? Well, perhaps you know that. Everybody know the day he’s born on, but do you know what day was the 31st January 1883? No? Well, there must be some method to determine any day in any &#8230; <a href="/2012/04/24/computer-algorithms-how-to-determine-the-day-of-the-week/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: How to Determine the Day of the Week</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/05/08/computer-algorithms-determine-if-a-number-is-prime/" rel="bookmark" title="Computer Algorithms: Determine if a Number is Prime">Computer Algorithms: Determine if a Number is Prime </a></li>
<li><a href="/2012/01/02/computer-algorithms-interpolation-search/" rel="bookmark" title="Computer Algorithms: Interpolation Search">Computer Algorithms: Interpolation Search </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="/2011/11/04/how-to-check-if-a-date-is-more-or-less-than-a-month-ago-with-php/" rel="bookmark" title="How to Check if a Date is More or Less Than a Month Ago with PHP">How to Check if a Date is More or Less Than a Month Ago with PHP </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Do you know what day of the week was the day you were born? Monday or maybe Saturday? Well, perhaps you know that. Everybody know the day he’s born on, but do you know what day was the 31st January 1883? No? Well, there must be some method to determine any day in any century.</p>
<p>We know that 2012 started at Sunday. After we know that it’s easy to determine what day is the 2nd of January. It should be Monday. But things get a little more complex if we try to guess some date distant from January the 1st. Indeed 1st of Jan was on Sunday, but what day is 9th of May the same year. This is far more difficult to say. Of course we can go with a brute force approach and count from 1/Jan till 9/May, but that is quite slow and error prone.</p>
<figure id="attachment_3079" style="width: 619px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/FollowingDays.png"><img class="size-full wp-image-3079" title="Following Days" src="/wp-content/uploads/2012/04/FollowingDays.png" alt="Following Days" width="619" height="315" srcset="/wp-content/uploads/2012/04/FollowingDays.png 619w, /wp-content/uploads/2012/04/FollowingDays-300x152.png 300w" sizes="(max-width: 619px) 100vw, 619px" /></a><figcaption class="wp-caption-text">If 1st of January is Sunday the most logical thing to happen is 2nd of January to be Monday</figcaption></figure>
<p>So what we’ll do if we have to code a program that answers this question. The most easier way is to use a library. Almost every major library has built-in functions that can answer what day is on a given date. Such are date() in PHP or getDate() in JavaScript. But the question remains. How these library functions know the answer and how can we code such library function if our library doesn’t support such functionality?</p>
<p>There must be some algorithm to help us.<span id="more-3058"></span></p>
<h2>Overview</h2>
<p>Because months has different number of days, and most of them aren’t divisible by 7 without a remainder, months begin on different days. Thus if January begins on Sunday, the month of February the same year will begin on Wednesday. Of course in common years February has 28 days, which fortunately is divisible by 7 and thus February and March both begin on the same day, which is great, but isn’t true for leap years.</p>
<h3>What Do We Know About the Calendar</h3>
<p>First thing to know is that each week has exactly 7 days. We know also that a common year has 365 days, while a leap year has one day more &#8211; 366. Most of the months has 30 or 31 days, but February has only 28 days in common years and 29 in leap years.</p>
<p>Because 365 mod 7 = 1 in a common year each year begins exactly on the next day of the preceding year. Thus if 2011 started on Saturday, 2012 starts on Sunday. And yet again that is because 2011 is not a leap year.</p>
<figure id="attachment_3081" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/SomeStatistics.png"><img class="size-full wp-image-3081" title="Some Statistics" src="/wp-content/uploads/2012/04/SomeStatistics.png" alt="Some Statistics" width="620" height="254" srcset="/wp-content/uploads/2012/04/SomeStatistics.png 620w, /wp-content/uploads/2012/04/SomeStatistics-300x122.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">A week always has 7 days, while a year has different number of days depending on the fact whether it&#39;s a leap or not!</figcaption></figure>
<p>What else do we know? Because a week has exactly seven days only February (with its 28 days in a common year) is divisible by 7 (28 mod 7 = 0) and has exactly four weeks in it. Thus in a common year February and March start on a same day. Unfortunately that is not true about the other months.</p>
<p>All these things we know about the calendar are great, so we can make some conclusions. Although eleven of the months have either 30 or 31 days they don’t start on a same day, but some of the months do appear to start on a same day just because the number of days between them is divisible by 7 without a remainder.</p>
<p>Let’s take a look on some examples. For instance September has 30 days, as November, while October, which is in between them has 31 days. Thus 30+30+31 makes 91. Fortunately 91 mod 7 = 0. So for each year September and December start on the same day (as they are after February they don’t depend on leap years). The same thing occurs to April and July and the good news is that in leap years even January starts on the same day as April and July.</p>
<figure id="attachment_3082" style="width: 623px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/PeriodsofDaysDivisibleby7.png"><img class="size-full wp-image-3082" title="Periods of Days Divisible by 7" src="/wp-content/uploads/2012/04/PeriodsofDaysDivisibleby7.png" alt="Periods of Days Divisible by 7" width="623" height="508" srcset="/wp-content/uploads/2012/04/PeriodsofDaysDivisibleby7.png 623w, /wp-content/uploads/2012/04/PeriodsofDaysDivisibleby7-300x244.png 300w" sizes="(max-width: 623px) 100vw, 623px" /></a><figcaption class="wp-caption-text">Not only the number of days in February is divisible by 7. The sum of days of April, May and June is also divisible by 7!</figcaption></figure>
<p>Now we know that there are some relations between months. Thus if we know somehow that 13th of April is Monday, we’ll be sure that 13th of July is also Monday. Let’s see now a summary of these observations.</p>
<figure id="attachment_3083" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/CorrespondingMonthsinaCommonYear.png"><img class="size-full wp-image-3083" title="Corresponding Months in a Common Year" src="/wp-content/uploads/2012/04/CorrespondingMonthsinaCommonYear.png" alt="Corresponding Months in a Common Year" width="621" height="516" srcset="/wp-content/uploads/2012/04/CorrespondingMonthsinaCommonYear.png 621w, /wp-content/uploads/2012/04/CorrespondingMonthsinaCommonYear-300x249.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">In a common year some months correspond!</figcaption></figure>
<p>We can also refer the following diagram.</p>
<figure id="attachment_3086" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/TableofCorrespondingMonthsinaCommonYear.png"><img class="size-full wp-image-3086" title="Table of Corresponding Months in a Common Year" src="/wp-content/uploads/2012/04/TableofCorrespondingMonthsinaCommonYear.png" alt="Table of Corresponding Months in a Common Year" width="620" height="326" srcset="/wp-content/uploads/2012/04/TableofCorrespondingMonthsinaCommonYear.png 620w, /wp-content/uploads/2012/04/TableofCorrespondingMonthsinaCommonYear-300x157.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">It&#39;s clearer to see the corresponding months in a table view!</figcaption></figure>
<p>For leap years there are other corresponding months. Let’s take a look at the following image.</p>
<figure id="attachment_3087" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/CorrespondingMonthsinaLeapYear.png"><img class="size-full wp-image-3087" title="Corresponding Months in a Leap Year" src="/wp-content/uploads/2012/04/CorrespondingMonthsinaLeapYear.png" alt="Corresponding Months in a Leap Year" width="621" height="516" srcset="/wp-content/uploads/2012/04/CorrespondingMonthsinaLeapYear.png 621w, /wp-content/uploads/2012/04/CorrespondingMonthsinaLeapYear-300x249.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">Corresponding months in a leap year differs from corresponding months in a common year!</figcaption></figure>
<p>Another way to get the same information is the following table.</p>
<figure id="attachment_3088" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/TableofCorrespondingMonthsinaLeapYear.png"><img class="size-full wp-image-3088" title="Table of Corresponding Months in a Leap Year" src="/wp-content/uploads/2012/04/TableofCorrespondingMonthsinaLeapYear.png" alt="Table of Corresponding Months in a Leap Year" width="620" height="326" srcset="/wp-content/uploads/2012/04/TableofCorrespondingMonthsinaLeapYear.png 620w, /wp-content/uploads/2012/04/TableofCorrespondingMonthsinaLeapYear-300x157.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Table view is easier to remember!</figcaption></figure>
<p>We know also that leap years happen to occur once per four years. However if there is a common year like the year 2001, which will be the next year that is common and starts and corresponds exactly on 2001? Because of leap years we can have a year starting on one of the seven days of the week and to be either leap or common. This means just 14 combinations.</p>
<p>Following these observations we can refer the following table.</p>
<pre lang="PHP">1700–1799     4
1800–1899     2
1900–1999     0
2000–2099     6
2100–2199     4
2200–2299     2
2300–2399     0
2400–2499     6
2500–2599     4
2600–2699     2</pre>
<p>You can clearly see the pattern “6 4 2 0”</p>
<p>Here’s the month table.</p>
<pre lang="PHP">Month		Common  	Leap
January 	0  		6
February	3 		2
March		3		3
April		6		6
May		1		1
June		4		4
July		6		6
August  	2		2
September	5		5
October 	0		0
November	3		3
December	5		5</pre>
<p>Columns 2 and 3 differs only for January and February.</p>
<p>Clearly the day table is as follows.</p>
<pre lang="PHP">Sunday  	0
Monday  	1
Tuesday 	2
Wednesday	3
Thursday	4
Friday  	5
Saturday	6</pre>
<p>Now let’s go back to the algorithm.</p>
<p>Using these tables and applying a simple formula we can calculate what day was on some given date. Here are the steps of this algorithm.</p>
<ol>
<li>Get the number for the corresponding century from the centuries table;</li>
<li>Get the last two digits from the year;</li>
<li>Divide the number from step 2 by 4 and get it without the remainder;</li>
<li>Get the month number from the month table;</li>
<li>Sum the numbers from steps 1 to 4;</li>
<li>Divide it by 7 and take the remainder;</li>
<li>Find the result of step 6 in the days table;</li>
</ol>
<h2>Implementation</h2>
<p>First let&#8217;s take a look on a simple practical example of the example above and then the code. Let’s answer the question from the first paragraph of this post.</p>
<p>What day was on January 31st, 1883?</p>
<ol>
<li>Take a look at the centuries table: for 1800 &#8211; 1899 this is 2.</li>
<li>Get the last two digits from the year: 83.</li>
<li>Divide 83 by 4 without a remainder: 83/4 = 20</li>
<li>Get the month number from the month table: Jan = 0.</li>
<li>Sum the numbers from steps 1 to 4: 2 + 83 + 20 + 0 = 105.</li>
<li>Divide it by 7 and take the remainder: 105 mod 7 = 0</li>
<li>Find the result of step 6 in the days table: Sunday = 0.</li>
</ol>
<p>The following code in PHP do implements the algorithm above.</p>
<pre lang="PHP">
function get_century_code($century)
{
	// XVIII
	if (1700 <= $century &#038;&#038; $century <= 1799)
		return 4;
		
	// XIX
	if (1800 <= $century &#038;&#038; $century <= 1899)
		return 2;
		
	// XX
	if (1900 <= $century &#038;&#038; $century <= 1999)
		return 0;
		
	// XXI
	if (2000 <= $century &#038;&#038; $century <= 2099)
		return 6;
		
	// XXII
	if (2100 <= $century &#038;&#038; $century <= 2199)
		return 4;
		
	// XXIII
	if (2200 <= $century &#038;&#038; $century <= 2299)
		return 2;
		
	// XXIV
	if (2300 <= $century &#038;&#038; $century <= 2399)
		return 0;
		
	// XXV
	if (2400 <= $century &#038;&#038; $century <= 2499)
		return 6;
	
	// XXVI
	if (2500 <= $century &#038;&#038; $century <= 2599)
		return 4;
	
	// XXVII
	if (2600 <= $century &#038;&#038; $century <= 2699)
		return 2;
}

/**
 * Get the day of a given date
 * 
 * @param $date
 */
function get_day_from_date($date) 
{
	$months = array(
		1 => 0,		// January
		2 => 3,		// February
		3 => 3,		// March
		4 => 6,		// April
		5 => 1,		// May
		6 => 4,		// June
		7 => 6,		// July
		8 => 2,		// August
		9 => 5,		// September
		10 => 0,	// October
		11 => 3,	// November
		12 => 5,	// December
	);
	
	$days = array(
		0 => 'Sunday',
		1 => 'Monday',
		2 => 'Tuesday',
		3 => 'Wednesday',
		4 => 'Thursday',
		5 => 'Friday',
		6 => 'Saturday',
	);
	
	// calculate the date
	$dateParts = explode('-', $date);
	$century = substr($dateParts[2], 0, 2);
	$year = substr($dateParts[2], 2);
	
	// 1. Get the number for the corresponding century from the centuries table
	$a = get_century_code($dateParts[2]);

	// 2. Get the last two digits from the year
	$b = $year;
	
	// 3. Divide the number from step 2 by 4 and get it without the remainder
	$c = floor($year / 4);
	
	// 4. Get the month number from the month table
	$d = $months[$dateParts[1]];

	// 5. Sum the numbers from steps 1 to 4
	$e = $a + $b + $c + $d;
	
	// 6. Divide it by 7 and take the remainder
	$f = $e % 7;
	
	// 7. Find the result of step 6 in the days table
	return $days[$f];
}

// Sunday
echo get_day_from_date('31-1-1883');
</pre>
<h2>Application</h2>
<p>This algorithm can be applied in many different cases although most of the libraries has built-in functions that can do that. The only problem besides that is that there are much more efficient algorithms that don&#8217;t need additional space (tables) of data. However this algorithm isn&#8217;t difficult to implement and it gives a good outlook of some facts in the calendar.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/05/08/computer-algorithms-determine-if-a-number-is-prime/" rel="bookmark" title="Computer Algorithms: Determine if a Number is Prime">Computer Algorithms: Determine if a Number is Prime </a></li>
<li><a href="/2012/01/02/computer-algorithms-interpolation-search/" rel="bookmark" title="Computer Algorithms: Interpolation Search">Computer Algorithms: Interpolation Search </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="/2011/11/04/how-to-check-if-a-date-is-more-or-less-than-a-month-ago-with-php/" rel="bookmark" title="How to Check if a Date is More or Less Than a Month Ago with PHP">How to Check if a Date is More or Less Than a Month Ago with PHP </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/04/24/computer-algorithms-how-to-determine-the-day-of-the-week/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Boyer-Moore String Searching</title>
		<link>/2012/04/17/computer-algorithms-boyer-moore-string-search-and-matching/</link>
		<comments>/2012/04/17/computer-algorithms-boyer-moore-string-search-and-matching/#comments</comments>
		<pubDate>Tue, 17 Apr 2012 08:24:46 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Boyer–Moore string search algorithm]]></category>
		<category><![CDATA[Boyer–Moore–Horspool algorithm]]></category>
		<category><![CDATA[Computer programming]]></category>
		<category><![CDATA[Computer science]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[J Strother Moore]]></category>
		<category><![CDATA[Morris-Pratt algorithm]]></category>
		<category><![CDATA[natural language search]]></category>
		<category><![CDATA[pattern forward]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Rabin-Karp algorithm]]></category>
		<category><![CDATA[Rabin-Karp string search algorithm]]></category>
		<category><![CDATA[Robert S. Boyer]]></category>
		<category><![CDATA[search]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[String searching algorithm]]></category>
		<category><![CDATA[string searching algorithms]]></category>
		<category><![CDATA[Strlen]]></category>
		<category><![CDATA[Substring]]></category>

		<guid isPermaLink="false">/?p=3049</guid>
		<description><![CDATA[Introduction Have you ever asked yourself which is the algorithm used to find a word after clicking Ctrl+F and typing something? Well I guess you know the answer from the title, but in this article you’ll find out how exactly this is done. As we saw from the Morris-Pratt string searching we don’t need to &#8230; <a href="/2012/04/17/computer-algorithms-boyer-moore-string-search-and-matching/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Boyer-Moore String Searching</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/04/09/computer-algorithms-morris-pratt-string-searching/" rel="bookmark" title="Computer Algorithms: Morris-Pratt String Searching">Computer Algorithms: Morris-Pratt String Searching </a></li>
<li><a href="/2012/04/02/computer-algorithms-rabin-karp-string-searching/" rel="bookmark" title="Computer Algorithms: Rabin-Karp String Searching">Computer Algorithms: Rabin-Karp String Searching </a></li>
<li><a href="/2012/03/27/computer-algorithms-brute-force-string-matching/" rel="bookmark" title="Computer Algorithms: Brute Force String Matching">Computer Algorithms: Brute Force String Matching </a></li>
<li><a href="/2011/11/24/computer-algorithms-sequential-search/" rel="bookmark" title="Computer Algorithms: Sequential Search">Computer Algorithms: Sequential Search </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Have you ever asked yourself which is the algorithm used to find a word after clicking Ctrl+F and typing something? Well I guess you know the answer from the title, but in this article you’ll find out how exactly this is done.</p>
<p>As we saw from the <a href="/2012/04/09/computer-algorithms-morris-pratt-string-searching/" title="Computer Algorithms: Morris-Pratt String Searching">Morris-Pratt string searching</a> we don’t need to compare the text and the pattern character by character. Some comparisons can be skipped in order to improve the performance of the string searching. Indeed the <a href="/2012/03/27/computer-algorithms-brute-force-string-matching/" title="Computer Algorithms: Brute Force String Matching">brute force string searching</a> and the <a href="/2012/04/02/computer-algorithms-rabin-karp-string-searching/" title="Computer Algorithms: Rabin-Karp String Searching">Rabin-Karp algorithm</a> are quite slow only because they compare the pattern and the text character by character.</p>
<p>In the other hand the Morris-Pratt algorithm is a very good improvement of the brute force string searching, but the question remains. Is there any algorithm that is faster than Morris-Pratt &#8211; is there any way to skip more comparisons and to move the pattern faster.</p>
<p>It’s clear that if we have to find whether a single character is contained into a text we need at least &#8220;n&#8221; steps, where n is the length of the text. Once we have to find whether a pattern with the length of &#8220;m&#8221; is contained into a text with length of &#8220;n&#8221; the case is getting a little more complex.</p>
<p>However the answer is that there is such algorithm that is faster and more suitable than Morris-Pratt. This is the Boyer-Moore string searching.</p>
<h2>Overview</h2>
<p>Boyer-Moore is an algorithm that improves the performance of pattern searching into a text by considering some observations. It is defined in 1977 by <a href="http://en.wikipedia.org/wiki/Robert_S._Boyer" title="Robert S. Boyer" target="_blank">Robert S. Boyer</a> and <a href="http://en.wikipedia.org/wiki/J_Strother_Moore" title="J Strother Moore" target="_blank">J Strother Moore</a> and it consist of some specific features. </p>
<p>First of all this algorithm starts comparing the pattern from the leftmost part of text and moves it to the right, as on the picture below.</p>
<p><figure id="attachment_3059" style="width: 618px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreShiftingDirection.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreShiftingDirection.png" alt="Boyer-Moore Shifting Direction" title="Boyer-Moore Shifting Direction" width="618" height="153" class="size-full wp-image-3059" srcset="/wp-content/uploads/2012/04/Boyer-MooreShiftingDirection.png 618w, /wp-content/uploads/2012/04/Boyer-MooreShiftingDirection-300x74.png 300w" sizes="(max-width: 618px) 100vw, 618px" /></a><figcaption class="wp-caption-text">In Boyer-Moore the pattern is shifted from left to right!</figcaption></figure><span id="more-3049"></span></p>
<p>Unlike other string searching algorithms though, Boyer-Moore compares the pattern against a possible match from right to left as shown below.</p>
<figure id="attachment_3066" style="width: 622px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreComparisonModel.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreComparisonModel.png" alt="Boyer-Moore Comparison Model" title="Boyer-Moore Comparison Model" width="622" height="169" class="size-full wp-image-3066" srcset="/wp-content/uploads/2012/04/Boyer-MooreComparisonModel.png 622w, /wp-content/uploads/2012/04/Boyer-MooreComparisonModel-300x81.png 300w" sizes="(max-width: 622px) 100vw, 622px" /></a><figcaption class="wp-caption-text">Unlike other algorithms the letters of the pattern are compared from right to left!</figcaption></figure>
<p>The main idea of Boyer-Moore in order to improve the performance are some observations of the pattern. In the terminology of this algorithm they are called good-suffix and bad-character shifts. Let’s see by the following examples what they are standing for.</p>
<h3>Good-suffix Shifts</h3>
<p>Just like the Morris-Pratt algorithm we start to compare the pattern against some portion of the text where a possible match will occur. In Boyer-Moore as I said this is done from the rightmost letter of the pattern. After some characters have matched we find a mismatch.</p>
<figure id="attachment_3065" style="width: 622px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreAMismatch.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreAMismatch.png" alt="Boyer-Moore a Mismatch" title="Boyer-Moore a Mismatch" width="622" height="214" class="size-full wp-image-3065" srcset="/wp-content/uploads/2012/04/Boyer-MooreAMismatch.png 622w, /wp-content/uploads/2012/04/Boyer-MooreAMismatch-300x103.png 300w" sizes="(max-width: 622px) 100vw, 622px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<p>So how can we move the pattern to the right in order to skip unusual comparisons. To answer this question we need to explore the pattern. Let’s say there is a portion of the pattern that is repeated inside the pattern itself, like it is shown on the picture below.</p>
<figure id="attachment_3062" style="width: 622px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreGood-suffixShift1.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreGood-suffixShift1.png" alt="Boyer-Moore Good-suffix Shift 1" title="Boyer-Moore Good-suffix Shift 1" width="622" height="195" class="size-full wp-image-3062" srcset="/wp-content/uploads/2012/04/Boyer-MooreGood-suffixShift1.png 622w, /wp-content/uploads/2012/04/Boyer-MooreGood-suffixShift1-300x94.png 300w" sizes="(max-width: 622px) 100vw, 622px" /></a><figcaption class="wp-caption-text">The pattern may consist of repeating portions of characters!</figcaption></figure>
<p>In this case we must move the pattern thus the repeated portion must now align with its first occurrence in the pattern.</p>
<p>A variation of this case is when the portion from the pattern A overlaps with another portion that consists of the same characters.</p>
<figure id="attachment_3061" style="width: 622px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreGoodSuffixShift2.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreGoodSuffixShift2.png" alt="Boyer-Moore Good Suffix Shift 2" title="Boyer-Moore Good Suffix Shift 2" width="622" height="195" class="size-full wp-image-3061" srcset="/wp-content/uploads/2012/04/Boyer-MooreGoodSuffixShift2.png 622w, /wp-content/uploads/2012/04/Boyer-MooreGoodSuffixShift2-300x94.png 300w" sizes="(max-width: 622px) 100vw, 622px" /></a><figcaption class="wp-caption-text">Sometimes these portions may overlap!</figcaption></figure>
<p>Yet again the shift must align the second portion with its first occurrence. </p>
<p>Finally only a portion of A, let’s say &#8220;B&#8221;, can happen to occur in the very beginning of the pattern, as on the diagram below.</p>
<figure id="attachment_3060" style="width: 622px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreGoodSuffixShift3.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreGoodSuffixShift3.png" alt="Boyer-Moore Good Suffix Shift 3" title="Boyer-Moore Good Suffix Shift 3" width="622" height="195" class="size-full wp-image-3060" srcset="/wp-content/uploads/2012/04/Boyer-MooreGoodSuffixShift3.png 622w, /wp-content/uploads/2012/04/Boyer-MooreGoodSuffixShift3-300x94.png 300w" sizes="(max-width: 622px) 100vw, 622px" /></a><figcaption class="wp-caption-text">Only a sub-string of the pattern may re-occur at its front!</figcaption></figure>
<p>Now we must align the left end of the pattern with the rightmost occurrence of &#8220;B&#8221;.</p>
<h3>Bad Character Shifts</h3>
<p>Beside the good-suffix shifts the Boyer-Moore algorithm make use of the so called bad-character shifts. In case of a mismatch we can skip comparisons in case the character in the text doesn’t happen to appear in the pattern. To become clearer let’s see the following examples.</p>
<figure id="attachment_3064" style="width: 623px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreBadCharacter1.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreBadCharacter1.png" alt="Boyer-Moore Bad Character 1" title="Boyer-Moore Bad Character 1" width="623" height="237" class="size-full wp-image-3064" srcset="/wp-content/uploads/2012/04/Boyer-MooreBadCharacter1.png 623w, /wp-content/uploads/2012/04/Boyer-MooreBadCharacter1-300x114.png 300w" sizes="(max-width: 623px) 100vw, 623px" /></a><figcaption class="wp-caption-text">If the mismatched letter of the text appears in the pattern only in its front we can align it easily!</figcaption></figure>
<p>In the picture above we see that the mismatched character &#8220;B&#8221; from the text appears only in the beginning of the pattern. Thus we can simply shift the pattern to the right and align both characters B, skipping comparisons. An even better case is described by the following diagram where the mismatched letter isn’t contained into the pattern at all. Then we can shift forward the whole pattern.</p>
<figure id="attachment_3063" style="width: 623px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreBadCharacter2.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreBadCharacter2.png" alt="Boyer-Moore Bad Character 2" title="Boyer-Moore Bad Character 2" width="623" height="237" class="size-full wp-image-3063" srcset="/wp-content/uploads/2012/04/Boyer-MooreBadCharacter2.png 623w, /wp-content/uploads/2012/04/Boyer-MooreBadCharacter2-300x114.png 300w" sizes="(max-width: 623px) 100vw, 623px" /></a><figcaption class="wp-caption-text">In case the mismatched letter isn&#039;t contained into the pattern we move forward the pattern!</figcaption></figure>
<h3>Maximum of Good-suffix and Bad-Character shifts</h3>
<p>Boyer-Moore needs both good-suffix and bad-character shifts in order to speed up searching performance. After a mismatch the maximum of both is considered in order to move the pattern to the right.</p>
<h2>Complexity</h2>
<p>It&#8217;s clear that Boyer-Moore is faster than Morris-Pratt, but actually its worst-case complexity is O(n+m). The thing is that in natural language search Boyer-Moore does pretty well.</p>
<figure id="attachment_3073" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-Moore-Complexity.png"><img src="/wp-content/uploads/2012/04/Boyer-Moore-Complexity.png" alt="Boyer-Moore Complexity" title="Boyer-Moore Complexity" width="600" height="371" class="size-full wp-image-3073" srcset="/wp-content/uploads/2012/04/Boyer-Moore-Complexity.png 600w, /wp-content/uploads/2012/04/Boyer-Moore-Complexity-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text">Worst-case scenario of Boyer-Moore - O(m+n)</figcaption></figure>
<h2>Implementation</h2>
<p>Finally let’s see the implementation in <a href="/category/php/" title="PHP on stoimen.com">PHP</a>, which can be easily &#8220;transcribed&#8221; into any other programming language. The only thing we need is the structures for bad-character shifts and good-suffixes shifts.</p>
<pre lang="PHP">
<?php

/**
 * Pattern we're searching for
 *
 * @var string
 */
$pattern = 'gloria';

/**
 * The text we're searching in
 *
 * @var string
 */
$text = 'Sic transit gloria mundi, non transit gloria Gundi!';

/**
 * Calculates the suffixes for a given pattern
 *
 * @param string $pattern
 * @param array  $suffixes
 */
function suffixes($pattern, &#038;$suffixes)
{
   $m = strlen($pattern);

   $suffixes[$m - 1] = $m;
   $g = $m - 1;

   for ($i = $m - 2; $i >= 0; --$i) {
      if ($i > $g && $suffixes[$i + $m - 1 - $f] < $i - $g) {
         $suffixes[$i] = $suffixes[$i + $m - 1 - $f];
      } else {
         if ($i < $g) {
            $g = $i;
         }
         $f = $i;
         	
         while ($g >= 0 && $pattern[$g] == $pattern[$g + $m - 1 - $f]) {
            $g--;
         }
         $suffixes[$i] = $f - $g;
      }
   }
}

/**
 * Fills in the array of bad characters.
 *
 * @param string $pattern
 * @param array  $badChars
 */
function badCharacters($pattern, &$badChars)
{
   $m = strlen($pattern);

   for ($i = 0; $i < $m - 1; ++$i) {
      $badChars[$pattern{$i}] = $m - $i - 1;
   }
}

/**
 * Fills in the array of good suffixes
 *
 * @param string $pattern
 * @param array  $goodSuffixes
 */
function goodSuffixes($pattern, &#038;$goodSuffixes)
{
   $m 		= strlen($pattern);
   $suff 	= array();

   suffixes($pattern, $suff);

   for ($i = 0; $i < $m; $i++) {
      $goodSuffixes[$i] = $m;
   }

   for ($i = $m - 1; $i >= 0; $i--) {
      if ($suff[$i] == $i + 1) {
         for ($j = 0; $j < $m - $i - 1; $j++) {
            if ($goodSuffixes[$j] == $m) {
               $goodSuffixes[$j] = $m - $i - 1;
            }
         }
      }
   }

   for ($i = 0; $i < $m - 2; $i++) {
      $goodSuffixes[$m - 1 - $suff[$i]] = $m - $i - 1;
   }
}

/**
 * Performs a search of the pattern into a given text
 *
 * @param string $pattern
 * @param string $text
 */
function boyer_moore($pattern, $text)
{
   $n = strlen($text);
   $m = strlen($pattern);

   $goodSuffixes 	= array();
   $badCharacters 	= array();

   goodSuffixes($pattern, &#038;$goodSuffixes);
   badCharacters($pattern, &#038;$badCharacters);

   $j = 0;
   while ($j < $n - $m) {
      for ($i = $m - 1; $i >= 0 && $pattern[$i] == $text[$i + $j]; $i--);
      if ($i < 0) {
         // note that if the substring occurs more
         // than once into the text, the algorithm will
         // print out each position of the substring
         echo $j;
         $j += $goodSuffixes[0];
      } else {
         $j += max($goodSuffixes[$i], $badCharacters[$text[$i + $j]] - $m + $i + 1);
      }
   }
}

// search using Boyer-Moore
// will return 12 and 38
boyer_moore($pattern, $text);
</pre>
<h2>Application</h2>
<p>Boyer-Moore is one of the most used string searching algorithm in practice. It is intuitively clear where it can be useful, but yet again I’ll say only that this algorithm is considered as the mostly used in practice for search and replace operations in text editors.</p>
<figure id="attachment_3068" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreApplication.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreApplication.png" alt="Boyer-Moore Application" title="Boyer-Moore Application" width="620" height="399" class="size-full wp-image-3068" srcset="/wp-content/uploads/2012/04/Boyer-MooreApplication.png 620w, /wp-content/uploads/2012/04/Boyer-MooreApplication-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/04/09/computer-algorithms-morris-pratt-string-searching/" rel="bookmark" title="Computer Algorithms: Morris-Pratt String Searching">Computer Algorithms: Morris-Pratt String Searching </a></li>
<li><a href="/2012/04/02/computer-algorithms-rabin-karp-string-searching/" rel="bookmark" title="Computer Algorithms: Rabin-Karp String Searching">Computer Algorithms: Rabin-Karp String Searching </a></li>
<li><a href="/2012/03/27/computer-algorithms-brute-force-string-matching/" rel="bookmark" title="Computer Algorithms: Brute Force String Matching">Computer Algorithms: Brute Force String Matching </a></li>
<li><a href="/2011/11/24/computer-algorithms-sequential-search/" rel="bookmark" title="Computer Algorithms: Sequential Search">Computer Algorithms: Sequential Search </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/04/17/computer-algorithms-boyer-moore-string-search-and-matching/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Morris-Pratt String Searching</title>
		<link>/2012/04/09/computer-algorithms-morris-pratt-string-searching/</link>
		<comments>/2012/04/09/computer-algorithms-morris-pratt-string-searching/#comments</comments>
		<pubDate>Mon, 09 Apr 2012 19:41:05 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Applied mathematics]]></category>
		<category><![CDATA[Boyer–Moore string search algorithm]]></category>
		<category><![CDATA[Brute-force search]]></category>
		<category><![CDATA[Complexity This algorithm]]></category>
		<category><![CDATA[Computer programming]]></category>
		<category><![CDATA[Computer science]]></category>
		<category><![CDATA[faster string searching algorithms]]></category>
		<category><![CDATA[James H. Morris]]></category>
		<category><![CDATA[Knuth–Morris–Pratt algorithm]]></category>
		<category><![CDATA[Lorem ipsum]]></category>
		<category><![CDATA[Morris-Pratt algorithm]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Rabin]]></category>
		<category><![CDATA[Rabin-Karp algorithm]]></category>
		<category><![CDATA[Rabin-Karp string search algorithm]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[String searching algorithm]]></category>
		<category><![CDATA[Vaughan Pratt]]></category>

		<guid isPermaLink="false">/?p=3019</guid>
		<description><![CDATA[Introduction We saw that neither brute force string searching nor Rabin-Karp string searching are effective. However in order to improve some algorithm, first we need to understand its principles in detail. We know already that brute force string matching is slow and we tried to improve it somehow by using a hash function in the &#8230; <a href="/2012/04/09/computer-algorithms-morris-pratt-string-searching/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Morris-Pratt String Searching</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/04/17/computer-algorithms-boyer-moore-string-search-and-matching/" rel="bookmark" title="Computer Algorithms: Boyer-Moore String Searching">Computer Algorithms: Boyer-Moore String Searching </a></li>
<li><a href="/2012/04/02/computer-algorithms-rabin-karp-string-searching/" rel="bookmark" title="Computer Algorithms: Rabin-Karp String Searching">Computer Algorithms: Rabin-Karp String Searching </a></li>
<li><a href="/2012/03/27/computer-algorithms-brute-force-string-matching/" rel="bookmark" title="Computer Algorithms: Brute Force String Matching">Computer Algorithms: Brute Force String Matching </a></li>
<li><a href="/2011/08/18/powerful-php-less-known-string-manipulation/" rel="bookmark" title="Powerful PHP: Less Known String Manipulation">Powerful PHP: Less Known String Manipulation </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>We saw that neither <a href="/2012/03/27/computer-algorithms-brute-force-string-matching/" title="Computer Algorithms: Brute Force String Matching">brute force string searching</a> nor <a href="/2012/04/02/computer-algorithms-rabin-karp-string-searching/" title="Computer Algorithms: Rabin-Karp String Searching">Rabin-Karp string searching</a> are effective. However in order to improve some algorithm, first we need to understand its principles in detail. We know already that brute force string matching is slow and we tried to improve it somehow by using a hash function in the Rabin-Karp algorithm. The problem is that Rabin-Karp has the same complexity as brute force string matching, which is O(mn).</p>
<p>Obviously we need a different approach, but to come with a different approach let’s see what’s wrong with brute force string searching. Indeed by taking a closer look at its principles we can answer the question. </p>
<p>In brute force matching we checked each character of the text with the first character of the pattern. In case of a match we shifted the comparison between the second character of the pattern and the next character of the text. The problem is that in case of a mismatch we must go several positions back in the text. Well in fact this technique can’t be optimized. </p>
<p><figure id="attachment_3025" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Morris-Pratt-brute-force-string-matching.png"><img src="/wp-content/uploads/2012/04/Morris-Pratt-brute-force-string-matching.png" alt="Morris-Pratt brute force string matching" title="Morris-Pratt brute force string matching" width="620" height="360" class="size-full wp-image-3025" srcset="/wp-content/uploads/2012/04/Morris-Pratt-brute-force-string-matching.png 620w, /wp-content/uploads/2012/04/Morris-Pratt-brute-force-string-matching-300x174.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">In brute force string matching in case of a mismatch we go back and we compare characters that has been compared already!</figcaption></figure><span id="more-3019"></span></p>
<p>As you can see on the picture above the problem is that once there is a mismatch we must rollback and start comparing from a position in the text that has been explored already. In our case we have checked the first, second, third and fourth letters, where there is a mismatch between the pattern and the text and then &#8230; we go back and start comparing from the second letter of the text.</p>
<p>This is completely useless, because we already know that the pattern begins with the letter “a” and no such letter happens to be between positions 1 and 3. So how can we improve this redundancy?</p>
<h2>Overview</h2>
<p>The answer of the question came to <a href="http://en.wikipedia.org/wiki/James_H._Morris" title="James H. Morris" target="_blank">James H. Morris</a> and <a href="http://en.wikipedia.org/wiki/Vaughan_Pratt" title="Vaughan Pratt" target="_blank">Vaughan Pratt</a> in 1977 when they described their algorithm, which by skipping lots of useless comparisons is more effective than brute force string matching. Let’s see it in detail. The only thing is to use the information gathered during the comparisons of the pattern and a possible match, as on the picture below.</p>
<figure id="attachment_3029" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Morris-Pratt-basic-principles.png"><img src="/wp-content/uploads/2012/04/Morris-Pratt-basic-principles.png" alt="Morris-Pratt basic principles" title="Morris-Pratt basic principles" width="620" height="483" class="size-full wp-image-3029" srcset="/wp-content/uploads/2012/04/Morris-Pratt-basic-principles.png 620w, /wp-content/uploads/2012/04/Morris-Pratt-basic-principles-300x233.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Morris-Pratt skips some comparisons by moving ahead to the next possible position of a match!</figcaption></figure>
<p>To do that first we have to preprocess the pattern in order to get possible positions for next matches. Thus after we start to find a possible match in case of a mismatch we’ll know exactly where we should jump in order to skip unusual comparisons.</p>
<h3>Generating the Table of Next Positions</h3>
<p>This is the tricky part in Morris-Pratt and that is how this algorithm overcomes the disadvantages of brute force string searching. Let&#8217;s see some pictures.</p>
<figure id="attachment_3044" style="width: 623px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Morris-Pratt-with-no-repeating-letters-in-the-pattern.png"><img src="/wp-content/uploads/2012/04/Morris-Pratt-with-no-repeating-letters-in-the-pattern.png" alt="Morris-Pratt with no repeating letters in the pattern" title="Morris-Pratt with no repeating letters in the pattern" width="623" height="361" class="size-full wp-image-3044" srcset="/wp-content/uploads/2012/04/Morris-Pratt-with-no-repeating-letters-in-the-pattern.png 623w, /wp-content/uploads/2012/04/Morris-Pratt-with-no-repeating-letters-in-the-pattern-300x173.png 300w" sizes="(max-width: 623px) 100vw, 623px" /></a><figcaption class="wp-caption-text">It is clear that if the pattern consists only of different letters in case of a mismatch we should start comparing the next character of the text with the first character of the pattern!</figcaption></figure>
<p>However in case of repeating character in the pattern if we have a mismatch after that character a possible match must begin from this repeating character, as on the picture bellow.</p>
<figure id="attachment_3045" style="width: 622px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Morris-Pratt-with-one-repeating-letter-in-the-pattern.png"><img src="/wp-content/uploads/2012/04/Morris-Pratt-with-one-repeating-letter-in-the-pattern.png" alt="Morris-Pratt with one repeating letter in the pattern" title="Morris-Pratt with one repeating letter in the pattern" width="622" height="404" class="size-full wp-image-3045" srcset="/wp-content/uploads/2012/04/Morris-Pratt-with-one-repeating-letter-in-the-pattern.png 622w, /wp-content/uploads/2012/04/Morris-Pratt-with-one-repeating-letter-in-the-pattern-300x194.png 300w" sizes="(max-width: 622px) 100vw, 622px" /></a><figcaption class="wp-caption-text">The next table is slightly different if the pattern has repeating character! </figcaption></figure>
<p>Finally if there are more than one repeating character in the text the &#8220;next&#8221; table will consist show their position.</p>
<figure id="attachment_3046" style="width: 622px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Morris-Pratt-more-than-one-repeating-letter-in-the-pattern.png"><img src="/wp-content/uploads/2012/04/Morris-Pratt-more-than-one-repeating-letter-in-the-pattern.png" alt="Morris-Pratt more than one repeating letter in the pattern" title="Morris-Pratt more than one repeating letter in the pattern" width="622" height="461" class="size-full wp-image-3046" srcset="/wp-content/uploads/2012/04/Morris-Pratt-more-than-one-repeating-letter-in-the-pattern.png 622w, /wp-content/uploads/2012/04/Morris-Pratt-more-than-one-repeating-letter-in-the-pattern-300x222.png 300w" sizes="(max-width: 622px) 100vw, 622px" /></a><figcaption class="wp-caption-text">The next table contains the positions of repeating letters!</figcaption></figure>
<p>After we have this table of possible “next” positions we can start exploring the text for our pattern.</p>
<figure id="attachment_3027" style="width: 622px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Morris-Pratt.png"><img src="/wp-content/uploads/2012/04/Morris-Pratt.png" alt="Morris-Pratt" title="Morris-Pratt" width="622" height="550" class="size-full wp-image-3027" srcset="/wp-content/uploads/2012/04/Morris-Pratt.png 622w, /wp-content/uploads/2012/04/Morris-Pratt-300x265.png 300w" sizes="(max-width: 622px) 100vw, 622px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<h2>Implementation</h2>
<p>Implementing Morris-Pratt isn’t difficult. First we have to preprocess the pattern and then perform the search. The following <a href="/category/php/" title="PHP on stoimen.com">PHP</a> code shows you how to do that.</p>
<pre lang="PHP">
/**
 * Pattern
 * 
 * @var string
 */
$pattern = 'mollis';

/**
 * Text to search
 * 
 * @var string
 */
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque eleifend nisi viverra ipsum elementum porttitor quis at justo. Aliquam ligula felis, dignissim sit amet lobortis eget, lacinia ac augue. Quisque nec est elit, nec ultricies magna. Ut mi libero, dictum sit amet mollis non, aliquam et augue';

/**
 * Preprocess the pattern and return the "next" table
 * 
 * @param string $pattern
 */
function preprocessMorrisPratt($pattern, &$nextTable)
{
	$i = 0;
	$j = $nextTable[0] = -1;
	$len = strlen($pattern);
	
	while ($i < $len) {
		while ($j > -1 && $pattern[$i] != $pattern[$j]) {
			$j = $nextTable[$j];
		}
		
		$nextTable[++$i] = ++$j;
	}
}

/**
 * Performs a string search with the Morris-Pratt algorithm
 * 
 * @param string $text
 * @param string $pattern
 */
function MorrisPratt($text, $pattern)
{
	// get the text and pattern lengths
	$n = strlen($text);
	$m = strlen($pattern);
	$nextTable = array();
	
	// calculate the next table
	preprocessMorrisPratt($pattern, $nextTable);
	
	$i = $j = 0;
	while ($j < $n) {
		while ($i > -1 && $pattern[$i] != $text[$j]) {
			$i = $nextTable[$i];
		}
		$i++;
		$j++;
		if ($i >= $m) {
			return $j - $i;
		}
	}
	return -1;
}

// 275
echo MorrisPratt($text, $pattern);
</pre>
<h2>Complexity</h2>
<p>This algorithm needs some time and space for preprocessing. Thus the preprocess of the pattern can be done in O(m), where m is the length of the pattern, while the search itself needs O(m+n). The good news is that you can do the preprocess only once and then perform the search as many times as you wish!</p>
<p>The following chart shows the complexity O(n+m) compared with O(nm) for 5 letter patterns.</p>
<figure id="attachment_3026" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Morris-Pratt-complexity.png"><img src="/wp-content/uploads/2012/04/Morris-Pratt-complexity.png" alt="Morris-Pratt complexity" title="Morris-Pratt complexity" width="600" height="371" class="size-full wp-image-3026" srcset="/wp-content/uploads/2012/04/Morris-Pratt-complexity.png 600w, /wp-content/uploads/2012/04/Morris-Pratt-complexity-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text">After pre-processing with O(m) the complexity of searching is O(n+m). You can see on the chart how effective is Morris-Pratt string searching compared to brute force string searching!</figcaption></figure>
<h2>Application</h2>
<h3>Why it&#8217;s cool</h3>
<ol>
<li>Its searching complexity is O(m+n) which is faster than brute force and Rabin-Karp</li>
<li>It’s fairly easy to implement</li>
</ol>
<h3>Why it isn’t cool</h3>
<ol>
<li>It needs additional space and time &#8211; O(m) for pre-processing</li>
<li>It can be optimized a bit (Knuth-Morris-Pratt)</li>
</ol>
<h2>Final Words</h2>
<p>Obviously this algorithm is quite useful because it improves in some very elegant manner the brute force matching. In the other hand you must know that there are faster string searching algorithms like the Boyer-Moore algorithm. However the Morris-Pratt algorithm can be quite useful in many cases, so understanding its principles can be very handy.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/04/17/computer-algorithms-boyer-moore-string-search-and-matching/" rel="bookmark" title="Computer Algorithms: Boyer-Moore String Searching">Computer Algorithms: Boyer-Moore String Searching </a></li>
<li><a href="/2012/04/02/computer-algorithms-rabin-karp-string-searching/" rel="bookmark" title="Computer Algorithms: Rabin-Karp String Searching">Computer Algorithms: Rabin-Karp String Searching </a></li>
<li><a href="/2012/03/27/computer-algorithms-brute-force-string-matching/" rel="bookmark" title="Computer Algorithms: Brute Force String Matching">Computer Algorithms: Brute Force String Matching </a></li>
<li><a href="/2011/08/18/powerful-php-less-known-string-manipulation/" rel="bookmark" title="Powerful PHP: Less Known String Manipulation">Powerful PHP: Less Known String Manipulation </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/04/09/computer-algorithms-morris-pratt-string-searching/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Brute Force String Matching</title>
		<link>/2012/03/27/computer-algorithms-brute-force-string-matching/</link>
		<comments>/2012/03/27/computer-algorithms-brute-force-string-matching/#comments</comments>
		<pubDate>Tue, 27 Mar 2012 07:21:41 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Bitap algorithm]]></category>
		<category><![CDATA[Boyer–Moore string search algorithm]]></category>
		<category><![CDATA[brute force algorithms]]></category>
		<category><![CDATA[Computer science]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[pre-processing]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[sequential search]]></category>
		<category><![CDATA[software development]]></category>
		<category><![CDATA[String]]></category>
		<category><![CDATA[String algorithms]]></category>
		<category><![CDATA[string matching algorithm]]></category>
		<category><![CDATA[String searching algorithm]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[text processing software]]></category>

		<guid isPermaLink="false">/?p=2966</guid>
		<description><![CDATA[Introduction String matching is something crucial for database development and text processing software. Fortunately every modern programming language and library is full of functions for string processing that help us in our everyday work. However is great to understand their principles. String algorithms can be mainly divided into several categories. One of these categories is &#8230; <a href="/2012/03/27/computer-algorithms-brute-force-string-matching/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Brute Force String Matching</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/04/02/computer-algorithms-rabin-karp-string-searching/" rel="bookmark" title="Computer Algorithms: Rabin-Karp String Searching">Computer Algorithms: Rabin-Karp String Searching </a></li>
<li><a href="/2012/04/09/computer-algorithms-morris-pratt-string-searching/" rel="bookmark" title="Computer Algorithms: Morris-Pratt String Searching">Computer Algorithms: Morris-Pratt String Searching </a></li>
<li><a href="/2012/04/17/computer-algorithms-boyer-moore-string-search-and-matching/" rel="bookmark" title="Computer Algorithms: Boyer-Moore String Searching">Computer Algorithms: Boyer-Moore String Searching </a></li>
<li><a href="/2011/08/18/powerful-php-less-known-string-manipulation/" rel="bookmark" title="Powerful PHP: Less Known String Manipulation">Powerful PHP: Less Known String Manipulation </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>String matching is something crucial for database development and text processing software. Fortunately every modern programming language and library is full of functions for string processing that help us in our everyday work. However is great to understand their principles.</p>
<p>String algorithms can be mainly divided into several categories. One of these categories is string matching.</p>
<p>When we come to string matching the most basic approach is what is known as brute force, which means just to check every single character from the text to match against the pattern. In general we have a text and a pattern (most commonly shorter than the text). What we need to do is to answer the question whether this pattern appears into the text.</p>
<h2>Overview</h2>
<p>The principles of brute force string matching are quite simple. We must check for a match between the first characters of the pattern with the first character of the text as on the picture bellow.</p>
<p><figure id="attachment_2977" style="width: 618px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/FirstStepBruteforcestringmatching.png"><img src="/wp-content/uploads/2012/03/FirstStepBruteforcestringmatching.png" alt="First step of brute force string matching" title="First step of brute force string matching" width="618" height="236" class="size-full wp-image-2977" srcset="/wp-content/uploads/2012/03/FirstStepBruteforcestringmatching.png 618w, /wp-content/uploads/2012/03/FirstStepBruteforcestringmatching-300x114.png 300w" sizes="(max-width: 618px) 100vw, 618px" /></a><figcaption class="wp-caption-text">We start by comparing the first characters of the text and the pattern!</figcaption></figure> <span id="more-2966"></span><br />
If they don’t match we move forward the second character of the text. Now we compare the first character of the pattern with the second character of the text. If they don’t match again we move forward until we get a match or until we reach the end of the text. </p>
<figure id="attachment_2982" style="width: 612px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/SecondStepBruteforcestringmatching.png"><img src="/wp-content/uploads/2012/03/SecondStepBruteforcestringmatching.png" alt="Second step of brute force string matching" title="Second step of brute force string matching" width="612" height="241" class="size-full wp-image-2982" srcset="/wp-content/uploads/2012/03/SecondStepBruteforcestringmatching.png 612w, /wp-content/uploads/2012/03/SecondStepBruteforcestringmatching-300x118.png 300w" sizes="(max-width: 612px) 100vw, 612px" /></a><figcaption class="wp-caption-text">Because the first character of the text and the pattern don&#039;t match, we move forward the second character of the text. Now we compare the second character of the text with the first character of the pattern!</figcaption></figure>
<p>In case they match we move forward the second character of the pattern comparing it with the “next” character of the text, as on the picture bellow.</p>
<figure id="attachment_2981" style="width: 617px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/ThirdStepBruteforcestringmatching.png"><img src="/wp-content/uploads/2012/03/ThirdStepBruteforcestringmatching.png" alt="Third step of  brute force string matching" title="Third step of  brute force string matching" width="617" height="235" class="size-full wp-image-2981" srcset="/wp-content/uploads/2012/03/ThirdStepBruteforcestringmatching.png 617w, /wp-content/uploads/2012/03/ThirdStepBruteforcestringmatching-300x114.png 300w" sizes="(max-width: 617px) 100vw, 617px" /></a><figcaption class="wp-caption-text">If case a character from the text match against the first character of the pattern we move forward to the second character of the pattern and the next character of the text!</figcaption></figure>
<p>Just because we have found a match between the first character from the pattern with some character of the text, doesn’t mean that the pattern appears in the text. We must move forward to see whether the full pattern is contained into the text. </p>
<figure id="attachment_2980" style="width: 619px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/MatchBruteforcestringmatching.png"><img src="/wp-content/uploads/2012/03/MatchBruteforcestringmatching.png" alt="Match in brute force string matching" title="Match in brute force string matching" width="619" height="229" class="size-full wp-image-2980" srcset="/wp-content/uploads/2012/03/MatchBruteforcestringmatching.png 619w, /wp-content/uploads/2012/03/MatchBruteforcestringmatching-300x110.png 300w" sizes="(max-width: 619px) 100vw, 619px" /></a><figcaption class="wp-caption-text">The pattern is matched!</figcaption></figure>
<h2>Implementation</h2>
<p>Implementation of brute force string matching is easy and here we can see a short PHP example. The bad news is that naturally this algorithm is quite slow.</p>
<pre lang="PHP">
function sub_string($pattern, $subject) 
{
	$n = strlen($subject);
	$m = strlen($pattern);
	
	for ($i = 0; i < $n-$m; $i++) {
		$j = 0;
		while ($j < $m &#038;&#038; $subject[$i+$j] == $pattern[$j]) {
			$j++;
		}
		if ($j == $m) return $i;
	}
	return -1;
}

echo sub_string('o wo', 'hello world!');

</pre>
<h2>Complexity</h2>
<p>As I said this algorithm is slow. Actually every algorithm that contains “brute force” in its name is slow, but to show how slow is string matching I can say that its complexity is O(n.m). Here <strong>n</strong> is the length of the text, while <strong>m</strong> is the length of the pattern.</p>
<figure id="attachment_2978" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/BruteForceStringMatchingComplexityChart1.png"><img src="/wp-content/uploads/2012/03/BruteForceStringMatchingComplexityChart1.png" alt="Brute force string matching complexity chart 1" title="Brute force string matching complexity chart 1" width="600" height="371" class="size-full wp-image-2978" srcset="/wp-content/uploads/2012/03/BruteForceStringMatchingComplexityChart1.png 600w, /wp-content/uploads/2012/03/BruteForceStringMatchingComplexityChart1-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text">For fixed pattern length of m = 5, we can see that even for relatively short text the time grows quickly!</figcaption></figure>
<p>In case we fix the length of the text and test against variable length of the pattern, again we get rapidly growing function.</p>
<figure id="attachment_2979" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/BruteForceStringMatchingComplexityChart2.png"><img src="/wp-content/uploads/2012/03/BruteForceStringMatchingComplexityChart2.png" alt="Brute force string matching complexity chart 2" title="Brute force string matching complexity chart 2" width="600" height="371" class="size-full wp-image-2979" srcset="/wp-content/uploads/2012/03/BruteForceStringMatchingComplexityChart2.png 600w, /wp-content/uploads/2012/03/BruteForceStringMatchingComplexityChart2-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<h2>Application</h2>
<p>Brute force string matching can be very ineffective, but it can also be very handy in some cases. Just like the <a href="/2011/11/24/computer-algorithms-sequential-search/" title="Computer Algorithms: Sequential Search">sequential search</a>.</p>
<h3>It can be very useful ...</h3>
<ol>
<li>Doesn't require pre-processing of the text - Indeed if we search the text only once we don't need to pre-process it. Most of the algorithms for string matching need to build an index of the text in order to search quickly. This is great when you've to search more than once into a text, but if you do only once, perhaps (for short texts) brute force matching is great!</li>
<li>Doesn't require additional space - Because brute force matching doesn't need pre-processing it also doesn't require more space, which is one cool feature of this algorithm</li>
<li>Can be quite effective for short texts and patterns</li>
</ol>
<h3>It can be ineffective ...</h3>
<ol>
<li>If we search more than once the text - As I said in the previous section if you perform the search more than once it's perhaps better to use another string matching algorithm that builds an index and it's faster.</li>
<li>It's slow - In general brute force algorithms are slow and brute force matching isn't an exception.</li>
</ol>
<h2>Final Words</h2>
<p>String matching is something very special in software development and it is used in various cases, so every developer must be familiar with this topic.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/04/02/computer-algorithms-rabin-karp-string-searching/" rel="bookmark" title="Computer Algorithms: Rabin-Karp String Searching">Computer Algorithms: Rabin-Karp String Searching </a></li>
<li><a href="/2012/04/09/computer-algorithms-morris-pratt-string-searching/" rel="bookmark" title="Computer Algorithms: Morris-Pratt String Searching">Computer Algorithms: Morris-Pratt String Searching </a></li>
<li><a href="/2012/04/17/computer-algorithms-boyer-moore-string-search-and-matching/" rel="bookmark" title="Computer Algorithms: Boyer-Moore String Searching">Computer Algorithms: Boyer-Moore String Searching </a></li>
<li><a href="/2011/08/18/powerful-php-less-known-string-manipulation/" rel="bookmark" title="Powerful PHP: Less Known String Manipulation">Powerful PHP: Less Known String Manipulation </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/03/27/computer-algorithms-brute-force-string-matching/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Data Compression with Prefix Encoding</title>
		<link>/2012/02/06/computer-algorithms-data-compression-with-prefix-encoding/</link>
		<comments>/2012/02/06/computer-algorithms-data-compression-with-prefix-encoding/#respond</comments>
		<pubDate>Mon, 06 Feb 2012 20:50:58 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Apple Inc.]]></category>
		<category><![CDATA[Computer science]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Data compression]]></category>
		<category><![CDATA[Decoder]]></category>
		<category><![CDATA[Delta encoding]]></category>
		<category><![CDATA[Dictionary coder]]></category>
		<category><![CDATA[Google Inc.]]></category>
		<category><![CDATA[Johnson Clarkson Jackson]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[mobile device]]></category>
		<category><![CDATA[same algorithm]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[Trie]]></category>
		<category><![CDATA[United Kingdom]]></category>
		<category><![CDATA[Yahoo! Inc.]]></category>

		<guid isPermaLink="false">/?p=2699</guid>
		<description><![CDATA[Overview Prefix encoding, sometimes called front encoding, is yet another algorithm that tries to remove duplicated data in order to reduce its size. Its principles are simple, however this algorithm tend to be difficult to implement. To understand why, first let’s take a look of its nature. Please, have a look on the following dictionary. &#8230; <a href="/2012/02/06/computer-algorithms-data-compression-with-prefix-encoding/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Data Compression with Prefix Encoding</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/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>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Overview</h2>
<p>Prefix encoding, sometimes called front encoding, is yet another algorithm that tries to remove duplicated data in order to reduce its size. Its principles are simple, however this algorithm tend to be difficult to implement. To understand why, first let’s take a look of its nature.</p>
<p>Please, have a look on the following dictionary.</p>
<pre lang="PHP">
use
used
useful
usefully
usefulness
useless
uselessly
uselessness
</pre>
<p>Instead of keeping all these words in plain text or transferring all them over a network, we can compress (encode) them with prefix encoding. </p>
<p><figure id="attachment_2700" style="width: 299px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/Prefixencoding.png"><img src="/wp-content/uploads/2012/02/Prefixencoding.png" alt="Prefix Encoding" title="Prefix encoding" width="299" height="457" class="size-full wp-image-2700" srcset="/wp-content/uploads/2012/02/Prefixencoding.png 299w, /wp-content/uploads/2012/02/Prefixencoding-196x300.png 196w" sizes="(max-width: 299px) 100vw, 299px" /></a><figcaption class="wp-caption-text"> </figcaption></figure><br />
<span id="more-2699"></span><br />
It’s clear that each of these words begin with the prefix “use” which is also the first word from the list. So we can easily compress them into the following array.</p>
<pre lang="PHP">
$data = array(
0 => 'use',
1 => '0d',
2 => '0ful',
3 => '0fully',
4 => '0less',
5 => '0lessly',
6 => '0lessness',
);
</pre>
<p>It’s clear that this is not the best compression and we can go even further by using not only the first word as prefix.</p>
<pre lang="PHP">
$data = array(
0 => 'use',
1 => '0d',
2 => '0ful',
3 => '2ly',
4 => '0less',
5 => '4ly',
6 => '4ness',
);
</pre>
<p>Now the compression is better and the good news is that decompression is a fairly simple process. However the tricky part is compression itself. The problem is that it is quite difficult to chose an appropriate prefix. In our first example this is simple, but most of the times in practice we can have more heterogeneous data. Indeed the process of compression can be very difficult for randomly generated data and the algorithm will be not only slow, but difficult to implement.</p>
<p>The good thing is that this algorithm can be used in many cases once we know the data format in advance. So let’s see three examples where this algorithm can be very handy.</p>
<h2>Application</h2>
<p>Here are three examples of prefix encoding. As I said above the process of compression can be very difficult for random data, so it is a good practice to use only it if you know in advance the format of the input data.</p>
<h3>Date and time prefixes</h3>
<p>We humans often skip the first two digits of an year, so for instance we don’t always write 1995 or 1996, but we use the shorter &#8211; ‘95 and ‘96. Thus years can be encoded with shorter strings.</p>
<pre lang="PHP">
input: 	(1991, 1992, 1993, 1994, 1995, 1996)
output:	(91, 92, 93, 94, 95, 96)
</pre>
<p>The problem is that with small changes of the input stream we can confuse the decoder. Thus if we add years from the 21st century we lose the uniqueness of the data.</p>
<pre lang="PHP">
input:	(1998, 1992, 1999, 2011, 2012)
output: (98, 92, 99, 11, 12)
</pre>
<p>Now the decoder can decode the last two values as (1911, 1912) as “19” is considered to be the prefix. So we must know in advance that our prefix is absolutely equal for each of the values. If not the encoding format must be different. For instance we can encode also the prefix, with some special maker.</p>
<pre lang="PHP">
input:	(1998, 1992, 1932, 1924, 2001, 2012)
output:	(#19, 98, 92, 32, 24, #20, 01, 12)
</pre>
<p>Once the decoder reads the # character it will know to decode the following number as prefix.</p>
<p>This can be used in practice for date and time formats. Let’s say we have some datetime values, but we know that all of them are in the same day.</p>
<pre lang="PHP">
2012-01-31 15:33:45
2012-01-31 16:12:11
2012-01-31 17:32:35
2012-01-31 18:54:34
</pre>
<p>Obviously we can omit the date part of these strings and send (keep) only the time. Once again, we must be absolutely sure that all these values are in the same day. If not, we can use the encoding strategy of the previous example.</p>
<h3>Phone numbers</h3>
<p>Phone numbers are the typical case of prefix encoding. Not only the international code, but also the mobile network operators use prefixes for their phone numbers. Thus if we have to transfer phone numbers from, let’s say the <strong>UK</strong>, we can replace the leading <strong>“+44”</strong> with something shorter. </p>
<p>If you happen to code a phone book for a mobile device you can spend some space by compressing the data using prefix encoding and thus the user will have more space and will store more phone numbers on his mobile.</p>
<p>Phone number prefixes can be also used for database normalization. Thus you can store them in a separate db table and leave only the unique numbers from the phonebook.</p>
<h3>Geo Coordinates</h3>
<p>Using the same example from <a href="/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/" title="Computer Algorithms: Data Compression with Relative Encoding">my previous post</a> we can send GEO coordinates by removing a common prefix, for large levels of zoom. Indeed when you’ve to send lots of markers to your map application you can expect all of these markers to be fairly close to each other in large zoom level.</p>
<figure id="attachment_2701" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/NY-map.png"><img src="/wp-content/uploads/2012/02/NY-map.png" alt="NY Subway Map" title="NY Subway Map" width="620" class="size-full wp-image-2701" srcset="/wp-content/uploads/2012/02/NY-map.png 843w, /wp-content/uploads/2012/02/NY-map-300x199.png 300w" sizes="(max-width: 843px) 100vw, 843px" /></a><figcaption class="wp-caption-text">On large zoom levels we can expect markers to be with the same prefix.</figcaption></figure>
<p>Now the coordinates of those points can have a common prefix, like the example bellow with the Subway stations.</p>
<pre lang="PHP">
LatLon(40.762959,-73.985989)
LatLon(40.761886,-73.983629)
LatLon(40.762861,-73.981612)
LatLon(40.764616,-73.98056)
</pre>
<p>We can see that all of these GEO points have the same prefix (40.76x, -73.98x), so we can send the prefix only once.</p>
<pre lang="PHP">
Prefix: (40.76, -73.98)
Data: 
LatLon(2959,5989)
LatLon(1886,3629)
LatLon(2861,1612)
LatLon(4616,056)
</pre>
<p>These are only three examples of prefix encoding and this algorithm must be considered as very useful when transferring homogeneous data. </p>
<h2>Suffix Encoding</h2>
<p>Suffix encoding practically the same algorithm as prefix encoding, with the small difference that we use to encode duplicating suffixes. Like the examples bellow suffix encoding can be useful is replacing repeating last name suffixes.</p>
<pre lang="PHP">
Johnson
Clarkson
Jackson
</pre>
<p>Or company names.</p>
<pre lang="PHP">
Apple Inc.
Google Inc.
Yahoo! Inc.
</pre>
<p>Here we can replace “ Inc.” with something else, but shorter.</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/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>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/02/06/computer-algorithms-data-compression-with-prefix-encoding/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution</title>
		<link>/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/</link>
		<comments>/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/#respond</comments>
		<pubDate>Mon, 23 Jan 2012 14:58:48 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Coding theory]]></category>
		<category><![CDATA[Computer file formats]]></category>
		<category><![CDATA[Computer science]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[conventional compressing tool]]></category>
		<category><![CDATA[Data compression]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[Information theory]]></category>
		<category><![CDATA[Lossy compression]]></category>
		<category><![CDATA[pattern substitution algorithm]]></category>
		<category><![CDATA[pattern substitution algorithms]]></category>
		<category><![CDATA[Pattern Substitution The pattern substitution algorithm]]></category>
		<category><![CDATA[Run-length encoding]]></category>
		<category><![CDATA[web hosting]]></category>

		<guid isPermaLink="false">/?p=2623</guid>
		<description><![CDATA[Overview Two variants of run-length encoding are the diagram encoding and the pattern substitution algorithms. The diagram encoding is actually a very simple algorithm. Unlike run-length encoding, where the input stream must consists of many repeating elements, as “aaaaaaaa” for instance, which are very rare in a natural language, there are many so called “diagrams” &#8230; <a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution</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/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/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>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Overview</h2>
<p>Two variants of <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> are the diagram encoding and the pattern substitution algorithms. The diagram encoding is actually a very simple algorithm. Unlike run-length encoding, where the input stream must consists of many repeating elements, as <strong>“aaaaaaaa”</strong> for instance, which are very rare in a natural language, there are many so called “diagrams” in almost any natural language. In plain English there are some diagrams as <strong>“the”</strong>, <strong>“and”</strong>, <strong>“ing”</strong> (in the word “waiting” for example), <strong>“ a”</strong>, <strong>“ t”</strong>, <strong>“ e”</strong> and many doubled letters. Actually we can extend those diagrams by adding surrounding spaces. Thus we can encode not only “the”, but “ the “, which are 5 characters (2 spaces and 3 letters) with something shorter. In the other hand, as I said, in plain English there are two many doubled letters, which unfortunately aren’t something special for run-length encoding and the compression ratio will be small. Even worse the encoded text may happen to be longer than the input message. Let’s see some examples.</p>
<p>Let’s say we’ve to encode the message “successfully accomplished”, which consists of four doubled letters. However to compress it with run-length encoding we’ll need at least 8 characters, which doesn’t help us a lot.</p>
<pre>
// 8 chars replaced by 8 chars!?
input: 	"successfully accomplished"
output:	"su2ce2sfu2ly a2complished"
</pre>
<p>The problem is that if the input text contains numbers, “2” in particular, we’ve to chose an escape symbol (“@” for example), which we’ll use to mark where the encoded run begins. Thus if the input message is “2 successfully accomplished tasks”, it will be encoded as “2 su@2ce@2sfu@2ly a@2complished tasks”. Now the output message is longer!!! than the input string.</p>
<pre>
// the compressed message is longer!!!
input:	"2 successfully accomplished"
output:	"2 su@2ce@2sfu@2ly a@2complished tasks"
</pre>
<p>Again if the input stream contains the escape symbol, we have to find another one, and the problem is that it is often too difficult to find short escape symbol that doesn’t appear in the input text, without a full scan of the text.<span id="more-2623"></span></p>
<p>That is why run-length encoding isn’t a good solution when compressing plain text, where long runs rarely appear. Well, of course, there are exceptions. For example such an exception is the lossy text compression with run-length encoding. It is intuitively clear that compressing text with loss is rarely useful, especially when you’ve to decompress exactly the same text. However there are some cases that lossy compression may be useful. Such case can be removing spaces. Indeed the text <strong>“successfully      accomplished”</strong> brings us exactly the same information as <strong>“successfully accomplished”</strong>. In this case we can simply remove those spaces. Indeed we can use a marker to indicate the long run of spaces like <strong>“successfully@6 accomplished”</strong> in order to decompress the input string with absolutely no loss, but we can also throw those symbols away. This desision depends on the goal. Exactly with the same goal in mind we can remove new lines and tabs, only if we’re sure that the sense of the text is preserved. Yet again, a problem is that such long runs don’t happen to occur in random texts. That is why it’s better to use diagram encoding for plain text compression instead of run-length encoding.</p>
<h2>Few Questions</h2>
<p>After understanding the principles of the diagram encoding, let’s see some examples. In the example above it is better to replace doubled letters with something shorter. Let’s say # for “cc”, @ for “ss” and % for “ll”. Thus the input text will be compressed as “su#e@fu%y a#omplished”,  which is shorter. But yet again what will happen if the input message contains one of the substitutions? Also we can’t say if there are many doubled letters and enough reasonable substitutions for them. A better approach is to replace patterns. </p>
<figure id="attachment_2640" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/DiagramEncodingonTexts.png"><img src="/wp-content/uploads/2012/01/DiagramEncodingonTexts.png" alt="Compressing texts with diagram encoding" title="Compressing texts with diagram encoding" width="620" class="size-full wp-image-2640" srcset="/wp-content/uploads/2012/01/DiagramEncodingonTexts.png 683w, /wp-content/uploads/2012/01/DiagramEncodingonTexts-300x128.png 300w" sizes="(max-width: 683px) 100vw, 683px" /></a><figcaption class="wp-caption-text">Run-length encoding isn&#039;t a good approach for text compression, because long runs rarely appear in a natural language.</figcaption></figure>
<h2>Pattern Substitution</h2>
<p>The pattern substitution algorithm is a variant of the diagram encoding. As I said above in plain English a very commonly used pattern can be “ the “, which is five characters long. We can now replace it with something like “$%” for example. In this case the message <strong>“I send the message”</strong> will become <strong>“I send$%message”</strong>. However there are some obstacles to overcome.</p>
<p>The first problem is that we need to know the language and somehow to define commonly used patterns in a dictionary. What would happen with a message written in some language we don’t know nothing about. Let’s say &#8211; Latin like the example bellow.</p>
<blockquote><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras venenatis, sapien eget suscipit placerat, justo quam blandit mauris, quis tempor ante sapien sodales augue. Praesent ut mauris quam. Phasellus scelerisque, ante quis consequat tristique, metus turpis consectetur leo, vitae facilisis sapien mi eu sapien. Praesent vitae ligula elit, et faucibus augue. Sed rhoncus sodales dolor ut gravida. In quis augue ac nulla auctor mattis sed sed libero. Donec eget purus eget enim tempor porta vitae eget diam. Mauris aliquet malesuada ipsum, non pulvinar urna vestibulum ac. Donec feugiat velit vitae nunc cursus imperdiet. Donec accumsan faucibus dictum. Phasellus sed mauris sapien. Maecenas mi metus, tincidunt sed rhoncus nec, sodales non sapien.</p></blockquote>
<p>Clearly without knowing Latin it isn’t easy to define which are those commonly used patterns. The thing is that it&#8217;s better to use pattern substitution if you know in advance the set of words and characters.</p>
<p>The second problem is related to decompression. It is obvious that we need to define a dictionary and this dictionary must be used when decoding the message. It will be great also if we find more patterns longer than three characters. If not, the compression ratio will be low. Unfortunately such patterns aren’t very common in any natural language.</p>
<figure id="attachment_2643" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/PatternSubstitutiononTexts.png"><img src="/wp-content/uploads/2012/01/PatternSubstitutiononTexts.png" alt="Text compression with diagram encoding and pattern substitution" title="Text compression with diagram encoding and pattern substitution" width="620" class="size-full wp-image-2643" srcset="/wp-content/uploads/2012/01/PatternSubstitutiononTexts.png 683w, /wp-content/uploads/2012/01/PatternSubstitutiononTexts-300x128.png 300w" sizes="(max-width: 683px) 100vw, 683px" /></a><figcaption class="wp-caption-text">Diagram encoding and pattern substitution are far more suitable for text compression than run-length encoding. In fact, pattern substitution is very effective on compressing programming languages.</figcaption></figure>
<h2>Application</h2>
<p>It is interesting to answer the question, how to use diagram encoding or patter substitution to compress text in natural language, especially when we don’t know the language in detail? The answer hides in the question. We wont compress natural languages, but machine language. Exactly machine (programming) languages are limited to a smaller sets of words and symbols. Isn’t it true for any programing language? Like PHP, where words like <strong>“function”</strong>, <strong>“while”</strong>, <strong>“for”</strong>, <strong>“break”</strong>, <strong>“switch”</strong>, <strong>“foreach”</strong> happen to be often in use, or HTML with its defined set of tags. Perhaps the best example is CSS, where only the values of the properties can vary. CSS files also tend to have multiple new lines, tabs and spaces, which only humans read.</p>
<p>The question here is why should we compress those file types. It’s clear that after the compression they will be completely useless, both for humans and machines. Yes, that is true, but what if we have to store versions of those files into a DB. Kind of a backup. Imagine you’re working for a web hosting company that has to store daily versions of the sites it’s hosting. Thus the volume of stored information even for small companies hosting only few sites can be enormous. The problem is that compressing those files with some conventional compressing tool isn’t a good idea. Thus we’ve to save a copy of the entire site every day, but as we know the difference between daily versions of a site can be small. A version control system is another solution, but then you’ve to store the plain text of the files. </p>
<p>Perhaps a better approach is to compress the text using pattern substitution and then saving only differences &#8211; kind of version control, which can be done with “relative encoding”.</p>
<p>Using the above method we can save lots of disk space and in the same time we can compress/decompress easily. Another good thing is that you can save only changes to the initial files, like version control, which can also be compressed.</p>
<h2>Implementation</h2>
<p>The implementation of this algorithm is again on PHP and tries only to describe the main principles of compression. In this case I tried to compress a CSS file using the compression above. Although this example is quite primitive we can see some interesting facts. First of all you only need encoding and decoding dictionaries. Practically the encoding and decoding processes are equal, so you don’t need to implement two different functions. Here in this example a native PHP function is used &#8211; str_replace, because the purpose of this algorithm is not to describe pattern substitution techniques, but pattern substitution. It assumes that today’s programming languages have string manipulation functions for the purposes of this task.</p>
<pre lang="PHP">
$str = file_get_contents('large_style_file.css');

$encoding_dict = array(
	"\n" 		=> '$0',
	'text' 		=> '$1',
	'color' 	=> '$2',
	'display' 	=> '$3',
	'font' 		=> '$4',
	'width' 	=> '$5',
	'height'	=> '$6',	
	' '		=> '',
);

function replace_patterns($input, $dict) 
{
	foreach ($dict as $pattern => $replace) {
		$input = str_replace($pattern, $replace, $input);
	}
	
	return $input;
}

$result = replace_patterns($str, $encoding_dict);
</pre>
<p>By only replacing few CSS properties I achieved almost 40% of compression ratio (as shows the diagram bellow). The initial file is 202 KB, while compressed it&#8217;s only 131 KB. Of course, it all depends on the CSS file, but how about replacing all property names with shorter ones. Perhaps then the compression will be even better.</p>
<figure id="attachment_2647" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/chart_1.png"><img src="/wp-content/uploads/2012/01/chart_1.png" alt="CSS compression with pattern substitution" title="CSS compression with pattern substitution" width="600" height="371" class="size-full wp-image-2647" srcset="/wp-content/uploads/2012/01/chart_1.png 600w, /wp-content/uploads/2012/01/chart_1-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/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/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/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>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Sequential Search</title>
		<link>/2011/11/24/computer-algorithms-sequential-search/</link>
		<comments>/2011/11/24/computer-algorithms-sequential-search/#comments</comments>
		<pubDate>Thu, 24 Nov 2011 09:25:35 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[Binary search algorithm]]></category>
		<category><![CDATA[Computer science]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[consecutive search]]></category>
		<category><![CDATA[forward sequential search]]></category>
		<category><![CDATA[Index]]></category>
		<category><![CDATA[ineffective searching algorithm]]></category>
		<category><![CDATA[ineffective searching algorithms]]></category>
		<category><![CDATA[Linear search]]></category>
		<category><![CDATA[linear search algorithm]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[reverse linear search approach]]></category>
		<category><![CDATA[search algorithm]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[sequential search]]></category>

		<guid isPermaLink="false">/?p=2483</guid>
		<description><![CDATA[Overview This is the easiest to implement and the most frequently used search algorithm in practice. Unfortunately the sequential search is also the most ineffective searching algorithm. However, it is so commonly used that it is appropriate to consider several ways to optimize it. In general the sequential search, also called linear search, is the &#8230; <a href="/2011/11/24/computer-algorithms-sequential-search/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Sequential Search</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2011/12/02/computer-algorithms-linear-search-in-sorted-lists/" rel="bookmark" title="Computer Algorithms: Linear Search in Sorted Lists">Computer Algorithms: Linear Search in Sorted Lists </a></li>
<li><a href="/2011/12/12/computer-algorithms-jump-search/" rel="bookmark" title="Computer Algorithms: Jump Search">Computer Algorithms: Jump Search </a></li>
<li><a href="/2011/12/26/computer-algorithms-binary-search/" rel="bookmark" title="Computer Algorithms: Binary Search">Computer Algorithms: Binary Search </a></li>
<li><a href="/2012/01/02/computer-algorithms-interpolation-search/" rel="bookmark" title="Computer Algorithms: Interpolation Search">Computer Algorithms: Interpolation Search </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Overview</h2>
<p>This is the easiest to implement and the most frequently used search algorithm in practice. Unfortunately the sequential search is also the most ineffective searching algorithm. However, it is so commonly used that it is appropriate to consider several ways to optimize it. In general the sequential search, also called linear search, is the method of consecutively check every value in a list until we find the desired one.</p>
<h2>Basic Implementation</h2>
<p>The most natural approach is to loop through the list until we find the desired value. Here’s an implementation on PHP using FOR loop, something that can be easily written into any other computer language.</p>
<p><script src="https://gist.github.com/stoimen/cdc433af43d3f396fd2b.js"></script></p>
<p>This is really the most ineffective implementation. There are two big mistakes in this code. First of all we calculate the length of the list on every iteration of the array, and secondly after we find the desired element, we don’t break the loop, but continue to loop through the array.</p>
<p><img src="/wp-content/uploads/2011/11/forward-linear-search.jpg" alt="Forward Linear Search" /></p>
<p>Yes, if the element is repeated without the “break” we can find its last occurrence, but if not the loop will iterate over the end of the array with no practical value.</p>
<h3>Optimization of the forward sequential search</h3>
<p><script src="https://gist.github.com/stoimen/94ec4473ac050fb0fedf.js"></script></p>
<p>&#8230; and javascript:</p>
<p><script src="https://gist.github.com/stoimen/21f1496da3488e2c8c9c.js"></script></p>
<p><img src="/wp-content/uploads/2011/11/optimized-forward-linear-search.jpg" alt="Optimized forward linear search" /></p>
<p>Even with this little optimization the algorithm remains ineffective. As we can see, on every iteration we have two conditional expressions. First we check whether we’ve reached the end of the list, and then we check whether the current element equals to the searched element. So the question is can we reduce the number of the conditional expressions?</p>
<h2>Searching in reverse order</h2>
<p>Yes, we can reduce the number of comparison instructions from the forward approach of the linear search algorithm by using reverse order searching. Although it seems to be pretty much the same by reversing the order of the search we can discard one of the conditional expressions.</p>
<p><script src="https://gist.github.com/stoimen/02c44ea1d8238d5f39dc.js?file=sequential_search_reverse.php"></script></p>
<p><em>Note that we need to adjust index because of $index—expression.</em></p>
<p>Indeed here we have only one conditional expression, but the problem is that this implementation is correct ONLY when the element exists in the list, which is not always true. If the element doesn’t appears into the list, then this code can lead to an infinite loop. OK, but how can we stop the loop even when the list doesn’t contain the desired value? The answer is, by adding the searched value to the list.</p>
<h2>Sentinel</h2>
<p>The above problem can be solved by inserting the desired item as a sentinel value. Thus we’re sure that the list contains the value, so the loop will stop for sure even if at the beginning the value didn’t appear to be part of the list.</p>
<p><img src="/wp-content/uploads/2011/11/sentinel-linear-search.jpg" alt="Using setinel in sequential search" /></p>
<p><script src="https://gist.github.com/stoimen/02c44ea1d8238d5f39dc.js?file=sequential_search_sentinel.php"></script></p>
<p>This approach can be used to overcome the problem of the reverse linear search approach from the previous section.</p>
<h2>Complexity</h2>
<p>As I said at the beginning of this post this is one of the most ineffective searching algorithms. Of course the best case is when the searched value is at the very beginning of the list. Thus on the first comparison we can find it. On the other hand the worst case is when the element is located at the very end of the list. Assuming that we don’t know where the element is and the possibility to be anywhere in the list is absolutely equal, then the complexity of this algorithm is O(n).</p>
<h3>Different cases</h3>
<p>We must remember, however, that the algorithm’s complexity can vary depending on whether the element occurs once.</p>
<h3>Is it so ineffective?</h3>
<p>Sequential search can be very slow compared to binary search on an ordered list. But actually this is not quite true. <strong>Sequential search can be faster than binary search</strong> for small arrays, but it is assumed that for n &lt; 8 the sequential search is faster.</p>
<h2>Application</h2>
<p>The linear search is really very simple to implement and most web developers go to the forward implementation, which is the most ineffective one. On the other hand this algorithm is quite useful when we search in an unordered list. Yes, searching in an ordered list is something that can dramatically change the search algorithm. Actually searching and sorting algorithms are often used together.</p>
<p>A typical case is pulling something from a database, usually in form of a list and then search for some value in it. Unfortunately in most of the cases the database orders the returned result set and yet most of the developers perform a consecutive search over the list. Yet again when the list is ordered it is better to use binary search instead of sequential search.<br />
Let’s say we have a CSV file containing the usernames and the names of our users.</p>
<pre><code>Username,Name
jamesbond007,James Bond
jsmith,John Smith
...
</code></pre>
<p>Now we fetch these values into an array.</p>
<pre><code>// work case
$arr = array(
    array('name' =&amp;gt; 'James Bond', 'username' =&amp;gt; 'jamesbond007'),
    array('name' =&amp;gt; 'John Smith', 'username' =&amp;gt; 'jsmith')
);
</code></pre>
<p>Now using sequential search &#8230;</p>
<pre><code>// using a sentinel
$x = 'jsmith';
$arr[] = array('username' =&amp;gt; $x, 'name' =&amp;gt; '');
$index = 0;

while ($arr[$index++]['username'] != $x);

if ($index &amp;lt; count($arr)) {
    echo "Hello, {$arr[$index-1]['name']}";
} else {
    echo "Hi, guest!";
}
</code></pre>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2011/12/02/computer-algorithms-linear-search-in-sorted-lists/" rel="bookmark" title="Computer Algorithms: Linear Search in Sorted Lists">Computer Algorithms: Linear Search in Sorted Lists </a></li>
<li><a href="/2011/12/12/computer-algorithms-jump-search/" rel="bookmark" title="Computer Algorithms: Jump Search">Computer Algorithms: Jump Search </a></li>
<li><a href="/2011/12/26/computer-algorithms-binary-search/" rel="bookmark" title="Computer Algorithms: Binary Search">Computer Algorithms: Binary Search </a></li>
<li><a href="/2012/01/02/computer-algorithms-interpolation-search/" rel="bookmark" title="Computer Algorithms: Interpolation Search">Computer Algorithms: Interpolation Search </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/11/24/computer-algorithms-sequential-search/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Looping Animation with JavaScript and Raphaël</title>
		<link>/2010/09/13/looping-animation-with-javascript-and-raphael/</link>
		<comments>/2010/09/13/looping-animation-with-javascript-and-raphael/#respond</comments>
		<pubDate>Mon, 13 Sep 2010 13:40:50 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[Animation]]></category>
		<category><![CDATA[Computer science]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Graphics file formats]]></category>
		<category><![CDATA[JavaScript library]]></category>
		<category><![CDATA[JavaScript programming language]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[Markup languages]]></category>
		<category><![CDATA[Raphael]]></category>
		<category><![CDATA[Scalable Vector Graphics]]></category>
		<category><![CDATA[Vector graphics markup languages]]></category>
		<category><![CDATA[Vector Markup Language]]></category>

		<guid isPermaLink="false">/?p=1980</guid>
		<description><![CDATA[Raphael is a popular JavaScript library helping you to manage vectors via SVG or VML in your browser. It is extremely helpful and very easy to learn and use. The interesting thing is that in the browser you can do very powerful things with vectors, but they remain very less known. However with such libraries &#8230; <a href="/2010/09/13/looping-animation-with-javascript-and-raphael/" class="more-link">Continue reading <span class="screen-reader-text">Looping Animation with JavaScript and Raphaël</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/06/14/javascript-array-pop-get-the-last-item/" rel="bookmark" title="JavaScript array.pop() &#8211; Get The Last Item">JavaScript array.pop() &#8211; Get The Last Item </a></li>
<li><a href="/2010/09/27/jquery-setting-up-a-vector-path-fill-color/" rel="bookmark" title="jQuery: Setting Up a Vector Path Fill Color">jQuery: Setting Up a Vector Path Fill Color </a></li>
<li><a href="/2010/09/24/2xjquery-select-a-selector/" rel="bookmark" title="2xjQuery: Select a Selector">2xjQuery: Select a Selector </a></li>
<li><a href="/2010/02/02/profiling-javascript-with-firebug-console-profile-console-time/" rel="bookmark" title="Profiling JavaScript with Firebug. console.profile() &#038; console.time()!">Profiling JavaScript with Firebug. console.profile() &#038; console.time()! </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p><a title="Raphael.js" href="http://raphaeljs.com/index.html" target="_blank">Raphael</a> is a popular JavaScript library helping you to manage vectors via SVG or VML in your browser. It is extremely helpful and very easy to learn and use. The interesting thing is that in the browser you can do very powerful things with vectors, but they remain very less known. However with such libraries like Raphael the task is really simple.</p>
<h2>Animation</h2>
<p>As I said animating some vector properties is as simple as:</p>
<pre lang="javascript">var paper = Raphael('canvas', 1024, 500);
var c = paper.circle(50, 50, 6).attr({fill : '#f00'});
c.animate({r : 10, fill : '#00f'}, 1000);
</pre>
<p>Here we change the radius and the background color of the circle for 1000 milliseconds.</p>
<p>The same thing can be done with any property with any other JavaScript library as <a title="jQuery" href="http://jquery.com/" target="_blank">jQuery</a>. But as in jQuery, Raphael or whatever library the animation is not looping. That&#8217;s natural you can just change a property by animating it, but the looping animation suggests at least two animations. So it&#8217;s a developers job to implement this. Here&#8217;s a simple way to do this.</p>
<h2>Two Way Animation</h2>
<p>The solution here is using two functions calling each other.</p>
<pre lang="javascript">
var paper = Raphael('canvas', 1024, 500);
var c = paper.circle(50, 50, 6).attr({fill : '#f00'});

function a() {
    c.animate({r : 10, fill : '#00f'}, 1000, b);
}
function b() {
    c.animate({r : 6, fill : '#f00'}, 1000, a);
}
a();
</pre>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/06/14/javascript-array-pop-get-the-last-item/" rel="bookmark" title="JavaScript array.pop() &#8211; Get The Last Item">JavaScript array.pop() &#8211; Get The Last Item </a></li>
<li><a href="/2010/09/27/jquery-setting-up-a-vector-path-fill-color/" rel="bookmark" title="jQuery: Setting Up a Vector Path Fill Color">jQuery: Setting Up a Vector Path Fill Color </a></li>
<li><a href="/2010/09/24/2xjquery-select-a-selector/" rel="bookmark" title="2xjQuery: Select a Selector">2xjQuery: Select a Selector </a></li>
<li><a href="/2010/02/02/profiling-javascript-with-firebug-console-profile-console-time/" rel="bookmark" title="Profiling JavaScript with Firebug. console.profile() &#038; console.time()!">Profiling JavaScript with Firebug. console.profile() &#038; console.time()! </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/09/13/looping-animation-with-javascript-and-raphael/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript Flexibility &#8211; Regex match()</title>
		<link>/2010/08/26/javascript-flexibility-regex-match/</link>
		<comments>/2010/08/26/javascript-flexibility-regex-match/#respond</comments>
		<pubDate>Thu, 26 Aug 2010 13:28:04 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[Computer programming]]></category>
		<category><![CDATA[Computer science]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[JavaScript programming language]]></category>
		<category><![CDATA[JavaScript syntax]]></category>
		<category><![CDATA[Technology/Internet]]></category>

		<guid isPermaLink="false">/?p=1927</guid>
		<description><![CDATA[Today after two posts [#1, #2] in the past days here&#8217;s something that shows again the JavaScript power. This is not a complete example, but it&#8217;s good to start. var str = '/text/1/text/2/'; var a = str.match(/(\d+)/gi); console.log(a); in that example you&#8217;ll get an array with all the numbers in the string [&#8220;1&#8221;, &#8220;2&#8221;] &#8211; &#8230; <a href="/2010/08/26/javascript-flexibility-regex-match/" class="more-link">Continue reading <span class="screen-reader-text">JavaScript Flexibility &#8211; Regex match()</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2011/07/12/a-javascript-trick-you-should-know/" rel="bookmark" title="A JavaScript Trick You Should Know">A JavaScript Trick You Should Know </a></li>
<li><a href="/2010/08/11/quick-look-at-javascript-objects/" rel="bookmark" title="Quick Look at JavaScript Objects">Quick Look at JavaScript Objects </a></li>
<li><a href="/2010/02/02/profiling-javascript-with-firebug-console-profile-console-time/" rel="bookmark" title="Profiling JavaScript with Firebug. console.profile() &#038; console.time()!">Profiling JavaScript with Firebug. console.profile() &#038; console.time()! </a></li>
<li><a href="/2010/08/24/flexible-javascript-splitting-strings/" rel="bookmark" title="Flexible JavaScript &#8211; Splitting Strings">Flexible JavaScript &#8211; Splitting Strings </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>Today after two posts [<a href="/2010/08/24/flexible-javascript-splitting-strings/" target="_blank">#1</a>, <a href="/2010/08/25/flexible-javascript-replace-in-a-string/" target="_blank">#2</a>] in the past days here&#8217;s something that shows again the JavaScript power. This is not a complete example, but it&#8217;s good to start.</p>
<pre lang="javascript">var str = '/text/1/text/2/';
var a = str.match(/(\d+)/gi);
console.log(a);
</pre>
<p>in that example you&#8217;ll get an array with all the numbers in the string [&#8220;1&#8221;, &#8220;2&#8221;] &#8211; yet another flexible js snippet!</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2011/07/12/a-javascript-trick-you-should-know/" rel="bookmark" title="A JavaScript Trick You Should Know">A JavaScript Trick You Should Know </a></li>
<li><a href="/2010/08/11/quick-look-at-javascript-objects/" rel="bookmark" title="Quick Look at JavaScript Objects">Quick Look at JavaScript Objects </a></li>
<li><a href="/2010/02/02/profiling-javascript-with-firebug-console-profile-console-time/" rel="bookmark" title="Profiling JavaScript with Firebug. console.profile() &#038; console.time()!">Profiling JavaScript with Firebug. console.profile() &#038; console.time()! </a></li>
<li><a href="/2010/08/24/flexible-javascript-splitting-strings/" rel="bookmark" title="Flexible JavaScript &#8211; Splitting Strings">Flexible JavaScript &#8211; Splitting Strings </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/08/26/javascript-flexibility-regex-match/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Flexible JavaScript &#8211; Replace in a String</title>
		<link>/2010/08/25/flexible-javascript-replace-in-a-string/</link>
		<comments>/2010/08/25/flexible-javascript-replace-in-a-string/#respond</comments>
		<pubDate>Wed, 25 Aug 2010 12:36:02 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[web development]]></category>
		<category><![CDATA[Computer science]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Curly bracket programming languages]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[JavaScript programming language]]></category>
		<category><![CDATA[JavaScript syntax]]></category>
		<category><![CDATA[Parameter]]></category>
		<category><![CDATA[Pattern matching]]></category>
		<category><![CDATA[Perl 6 rules]]></category>
		<category><![CDATA[Regular expression]]></category>
		<category><![CDATA[Scripting languages]]></category>
		<category><![CDATA[Software engineering]]></category>

		<guid isPermaLink="false">/?p=1923</guid>
		<description><![CDATA[Here&#8217;s yet another example of the JavaScript flexibility. You can simply call .replace() on every string and pass a regex as a parameter! var str = 'my simple string'; str.replace(/ /g, '-'); // now 'str' will contain 'my-simple-string'<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/08/24/flexible-javascript-splitting-strings/" rel="bookmark" title="Flexible JavaScript &#8211; Splitting Strings">Flexible JavaScript &#8211; Splitting Strings </a></li>
<li><a href="/2010/08/26/javascript-flexibility-regex-match/" rel="bookmark" title="JavaScript Flexibility &#8211; Regex match()">JavaScript Flexibility &#8211; Regex match() </a></li>
<li><a href="/2011/07/12/a-javascript-trick-you-should-know/" rel="bookmark" title="A JavaScript Trick You Should Know">A JavaScript Trick You Should Know </a></li>
<li><a href="/2011/08/18/powerful-php-less-known-string-manipulation/" rel="bookmark" title="Powerful PHP: Less Known String Manipulation">Powerful PHP: Less Known String Manipulation </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>Here&#8217;s yet another example of the JavaScript flexibility. You can simply call .replace() on every string and pass a regex as a parameter!</p>
<pre lang="javascript">
var str = 'my simple string';
str.replace(/ /g, '-'); // now 'str' will contain 'my-simple-string'
</pre>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/08/24/flexible-javascript-splitting-strings/" rel="bookmark" title="Flexible JavaScript &#8211; Splitting Strings">Flexible JavaScript &#8211; Splitting Strings </a></li>
<li><a href="/2010/08/26/javascript-flexibility-regex-match/" rel="bookmark" title="JavaScript Flexibility &#8211; Regex match()">JavaScript Flexibility &#8211; Regex match() </a></li>
<li><a href="/2011/07/12/a-javascript-trick-you-should-know/" rel="bookmark" title="A JavaScript Trick You Should Know">A JavaScript Trick You Should Know </a></li>
<li><a href="/2011/08/18/powerful-php-less-known-string-manipulation/" rel="bookmark" title="Powerful PHP: Less Known String Manipulation">Powerful PHP: Less Known String Manipulation </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/08/25/flexible-javascript-replace-in-a-string/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
