<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Code Overflow</title>
	<atom:link href="http://codeoverflow.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://codeoverflow.wordpress.com</link>
	<description>++++++++++&#091;&#62;+++++++&#62;++++++++&#62;+++&#60;&#60;&#60;-&#093;&#62;—&#032;-&#032;-&#032;&#032;-.&#62;-.&#60;+.+.&#62;&#62;++.&#60;.+++++++.&#60;.&#62;—&#032;-&#032;&#032;-&#032;&#032;-&#032;&#032;-.&#60;+.++++++.+++.&#62;+++++.&#032;&#032;</description>
	<lastBuildDate>Wed, 17 Aug 2011 08:27:12 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='codeoverflow.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Code Overflow</title>
		<link>http://codeoverflow.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://codeoverflow.wordpress.com/osd.xml" title="Code Overflow" />
	<atom:link rel='hub' href='http://codeoverflow.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Linear Recurrences</title>
		<link>http://codeoverflow.wordpress.com/2011/05/23/linear-recurrences/</link>
		<comments>http://codeoverflow.wordpress.com/2011/05/23/linear-recurrences/#comments</comments>
		<pubDate>Mon, 23 May 2011 16:47:53 +0000</pubDate>
		<dc:creator>SwitchCase</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[exponentiation]]></category>
		<category><![CDATA[fibonacci]]></category>
		<category><![CDATA[fibonacci in logN]]></category>
		<category><![CDATA[fibonacci using matrix]]></category>
		<category><![CDATA[linear recurrences]]></category>
		<category><![CDATA[logn]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[recursion using matrix]]></category>
		<category><![CDATA[recursion with matrix]]></category>

		<guid isPermaLink="false">http://codeoverflow.wordpress.com/?p=139</guid>
		<description><![CDATA[How often has it happened to you in a programming contest (or elsewhere) that you thought it was impossible to solve it faster than O(N) and yet the limits imposed suggest that it has to be done faster. Well, if not all, atleast a majority of them have a solution based on the idea of <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeoverflow.wordpress.com&amp;blog=17915630&amp;post=139&amp;subd=codeoverflow&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>H</strong>ow often has it happened to you in a programming contest (or elsewhere) that you thought it was impossible to solve it faster than O(N) and yet the limits imposed suggest that it has to be done faster. Well, if not all, atleast a majority of them have a solution based on the idea of linear recurrences. In this blog post, I intend to help you out on this !!</p>
<p>In this post, we are going to do a &#8211; Solve and Learn strategy ; You will be given a question and I will show you how to apply  the concepts on them.</p>
<h3><strong>TYPE 1 :: The Simplest :</strong></h3>
<p>If a post mentions recurrences, then it has to mention Fibonacci (Gosh, if only I had a penny for every mention of Fibo in tutorials. )</p>
<p>The recurrence is of type : F(n) = F(n-1) + F(n-2).</p>
<p>I am pretty sure you know to code the linear version of it which runs in O(N) but can you do it in O(log N) ? If you throw google to good use, you will come up with a solution which says there is a Matrix M which when raised to power N, will give you the N-th fibonacci number. And since you can always exponentiate in logN time, you have your answer. But to those, who wondered if this Matrix is magical- read on!</p>
<p>Firstly the answer- No; Its not magical. How. Lets do a little Algebra (yumm&#8230; My favourite! )<br />
<img src='http://s0.wp.com/latex.php?latex=F%28n%29%3DF%28n-1%29%2BF%28n-2%29%5C%5C+%5C%5C+F%28n%2B1%29+%3DF%28n%29%2BF%28n-1%29%5C%5C+%5C%5C+F%28n%2B2%29%3DF%28n%2B1%29%2BF%28n%29+&amp;bg=ffffff&amp;fg=666666&amp;s=0' alt='F(n)=F(n-1)+F(n-2)&#92;&#92; &#92;&#92; F(n+1) =F(n)+F(n-1)&#92;&#92; &#92;&#92; F(n+2)=F(n+1)+F(n) ' title='F(n)=F(n-1)+F(n-2)&#92;&#92; &#92;&#92; F(n+1) =F(n)+F(n-1)&#92;&#92; &#92;&#92; F(n+2)=F(n+1)+F(n) ' class='latex' /></p>
<p>Obviously enough, the value of N-th term, depends on two previous terms (or states). This implies that all values depend on just the first two states in the sequence. As you can see here -</p>
<p><img src='http://s0.wp.com/latex.php?latex=%5Cbegin%7Bpmatrix%7DF%28n%2B2%29%5C%5C+F%28n%2B1%29%5Cend%7Bpmatrix%7D%3D%5Cbegin%7Bpmatrix%7D1%261%5C%5C+1%260%5C%5C+%5Cend%7Bpmatrix%7D%5Ctimes%5Cbegin%7Bpmatrix%7DF%28n%2B1%29%5C%5C+F%28n%29%5Cend%7Bpmatrix%7D%5C%5C+%5C%5C+and%5C%5C+%5C%5C+%5Cbegin%7Bpmatrix%7DF%28n%2B1%29%5C%5C+F%28n%29%5Cend%7Bpmatrix%7D%3D%5Cbegin%7Bpmatrix%7D1%261%5C%5C+1%260%5C%5C+%5Cend%7Bpmatrix%7D+%5Ctimes+%5Cbegin%7Bpmatrix%7DF%28n%29%5C%5C+F%28n-1%29%5Cend%7Bpmatrix%7D+%5C%5C+%5C%5C+Hence+%5C%5C+%5C%5C+%5Cbegin%7Bpmatrix%7DF%28n%2B2%29%5C%5C+F%28n%2B1%29%5Cend%7Bpmatrix%7D%3D%5Cbegin%7Bpmatrix%7D1%261%5C%5C+1%260%5C%5C+%5Cend%7Bpmatrix%7D+%5E2+%5Ctimes+%5Cbegin%7Bpmatrix%7DF%28n%29%5C%5C+F%28n-1%29%5Cend%7Bpmatrix%7D+%5C%5C+%5C%5C+%5Cbegin%7Bpmatrix%7DF%28n%2B2%29%5C%5C+F%28n%2B1%29%5Cend%7Bpmatrix%7D%3D%5Cbegin%7Bpmatrix%7D1%261%5C%5C+1%260%5C%5C+%5Cend%7Bpmatrix%7D%5E3+%5Ctimes+%5Cbegin%7Bpmatrix%7DF%28n-1%29%5C%5C+F%28n-2%29%5Cend%7Bpmatrix%7D&amp;bg=ffffff&amp;fg=666666&amp;s=0' alt='&#92;begin{pmatrix}F(n+2)&#92;&#92; F(n+1)&#92;end{pmatrix}=&#92;begin{pmatrix}1&amp;1&#92;&#92; 1&amp;0&#92;&#92; &#92;end{pmatrix}&#92;times&#92;begin{pmatrix}F(n+1)&#92;&#92; F(n)&#92;end{pmatrix}&#92;&#92; &#92;&#92; and&#92;&#92; &#92;&#92; &#92;begin{pmatrix}F(n+1)&#92;&#92; F(n)&#92;end{pmatrix}=&#92;begin{pmatrix}1&amp;1&#92;&#92; 1&amp;0&#92;&#92; &#92;end{pmatrix} &#92;times &#92;begin{pmatrix}F(n)&#92;&#92; F(n-1)&#92;end{pmatrix} &#92;&#92; &#92;&#92; Hence &#92;&#92; &#92;&#92; &#92;begin{pmatrix}F(n+2)&#92;&#92; F(n+1)&#92;end{pmatrix}=&#92;begin{pmatrix}1&amp;1&#92;&#92; 1&amp;0&#92;&#92; &#92;end{pmatrix} ^2 &#92;times &#92;begin{pmatrix}F(n)&#92;&#92; F(n-1)&#92;end{pmatrix} &#92;&#92; &#92;&#92; &#92;begin{pmatrix}F(n+2)&#92;&#92; F(n+1)&#92;end{pmatrix}=&#92;begin{pmatrix}1&amp;1&#92;&#92; 1&amp;0&#92;&#92; &#92;end{pmatrix}^3 &#92;times &#92;begin{pmatrix}F(n-1)&#92;&#92; F(n-2)&#92;end{pmatrix}' title='&#92;begin{pmatrix}F(n+2)&#92;&#92; F(n+1)&#92;end{pmatrix}=&#92;begin{pmatrix}1&amp;1&#92;&#92; 1&amp;0&#92;&#92; &#92;end{pmatrix}&#92;times&#92;begin{pmatrix}F(n+1)&#92;&#92; F(n)&#92;end{pmatrix}&#92;&#92; &#92;&#92; and&#92;&#92; &#92;&#92; &#92;begin{pmatrix}F(n+1)&#92;&#92; F(n)&#92;end{pmatrix}=&#92;begin{pmatrix}1&amp;1&#92;&#92; 1&amp;0&#92;&#92; &#92;end{pmatrix} &#92;times &#92;begin{pmatrix}F(n)&#92;&#92; F(n-1)&#92;end{pmatrix} &#92;&#92; &#92;&#92; Hence &#92;&#92; &#92;&#92; &#92;begin{pmatrix}F(n+2)&#92;&#92; F(n+1)&#92;end{pmatrix}=&#92;begin{pmatrix}1&amp;1&#92;&#92; 1&amp;0&#92;&#92; &#92;end{pmatrix} ^2 &#92;times &#92;begin{pmatrix}F(n)&#92;&#92; F(n-1)&#92;end{pmatrix} &#92;&#92; &#92;&#92; &#92;begin{pmatrix}F(n+2)&#92;&#92; F(n+1)&#92;end{pmatrix}=&#92;begin{pmatrix}1&amp;1&#92;&#92; 1&amp;0&#92;&#92; &#92;end{pmatrix}^3 &#92;times &#92;begin{pmatrix}F(n-1)&#92;&#92; F(n-2)&#92;end{pmatrix}' class='latex' /></p>
<p>Hence in General, we may write ::<br />
<img src='http://s0.wp.com/latex.php?latex=%5Cbegin%7Bpmatrix%7DF%28n%29%5C%5C+F%28n-1%29%5Cend%7Bpmatrix%7D%3D%5Cbegin%7Bpmatrix%7D1%261%5C%5C+1%260%5C%5C+%5Cend%7Bpmatrix%7D%5E%7Bn-1%7D+%5Ctimes+%5Cbegin%7Bpmatrix%7D1%5C%5C+0%5Cend%7Bpmatrix%7D+&amp;bg=ffffff&amp;fg=666666&amp;s=0' alt='&#92;begin{pmatrix}F(n)&#92;&#92; F(n-1)&#92;end{pmatrix}=&#92;begin{pmatrix}1&amp;1&#92;&#92; 1&amp;0&#92;&#92; &#92;end{pmatrix}^{n-1} &#92;times &#92;begin{pmatrix}1&#92;&#92; 0&#92;end{pmatrix} ' title='&#92;begin{pmatrix}F(n)&#92;&#92; F(n-1)&#92;end{pmatrix}=&#92;begin{pmatrix}1&amp;1&#92;&#92; 1&amp;0&#92;&#92; &#92;end{pmatrix}^{n-1} &#92;times &#92;begin{pmatrix}1&#92;&#92; 0&#92;end{pmatrix} ' class='latex' /></p>
<p>I hope that has helped you in understanding how to frame such equations and solving it with a matrix.</p>
<h3><strong>TYPE 2 : Simplest ++</strong></h3>
<p>Now that we have a basic understanding. Try the following recurrence :</p>
<p>F(n) = F(n-1) + F(n-2) + F(n-3).</p>
<p>It is the same as the previous recurrence but with an additional state. I won&#8217;t go on explaining the hows (again!). I am going to share the solution.<br />
<img src='http://s0.wp.com/latex.php?latex=%5Cbegin%7Bpmatrix%7DF%28n%29%5C%5C+F%28n-1%29%5C%5C+F%28n-2%29+%5Cend%7Bpmatrix%7D%3D%5Cbegin%7Bpmatrix%7D1%261%261%5C%5C+1%260%260%5C%5C+0%261%260+%5Cend%7Bpmatrix%7D%5E%7Bn-2%7D+%5Ctimes+%5Cbegin%7Bpmatrix%7D2%5C%5C+1%5C%5C+1%5Cend%7Bpmatrix%7D+&amp;bg=ffffff&amp;fg=666666&amp;s=0' alt='&#92;begin{pmatrix}F(n)&#92;&#92; F(n-1)&#92;&#92; F(n-2) &#92;end{pmatrix}=&#92;begin{pmatrix}1&amp;1&amp;1&#92;&#92; 1&amp;0&amp;0&#92;&#92; 0&amp;1&amp;0 &#92;end{pmatrix}^{n-2} &#92;times &#92;begin{pmatrix}2&#92;&#92; 1&#92;&#92; 1&#92;end{pmatrix} ' title='&#92;begin{pmatrix}F(n)&#92;&#92; F(n-1)&#92;&#92; F(n-2) &#92;end{pmatrix}=&#92;begin{pmatrix}1&amp;1&amp;1&#92;&#92; 1&amp;0&amp;0&#92;&#92; 0&amp;1&amp;0 &#92;end{pmatrix}^{n-2} &#92;times &#92;begin{pmatrix}2&#92;&#92; 1&#92;&#92; 1&#92;end{pmatrix} ' class='latex' /></p>
<h3>TYPE 3: Simplest &lt;&lt; 1</h3>
<p>Consider the following scenario ::</p>
<p><img src='http://s0.wp.com/latex.php?latex=G%28n%29+%3D+a+.+G%28n-1%29+%2B+b+.+G%28n-2%29+%2B+c+.+H%28n%29%5C%5C+%5C%5C+and+%5C%5C+%5C%5C+H%28n%29%3D+d+.+H%28n-1%29+%2B+e+.+H%28n-2%29+&amp;bg=ffffff&amp;fg=666666&amp;s=0' alt='G(n) = a . G(n-1) + b . G(n-2) + c . H(n)&#92;&#92; &#92;&#92; and &#92;&#92; &#92;&#92; H(n)= d . H(n-1) + e . H(n-2) ' title='G(n) = a . G(n-1) + b . G(n-2) + c . H(n)&#92;&#92; &#92;&#92; and &#92;&#92; &#92;&#92; H(n)= d . H(n-1) + e . H(n-2) ' class='latex' /></p>
<p>This one is a lot trickier. First thing to notice is that we will need 4 states in a matrix to fully define the next state. The reason for using 4 and not 3 is that H(n) depends on 2 states and thus we need 2 states (and not just 1) to represent it.</p>
<p>If you carefully write down the LHS matrix and the RHS matrix, then we can frame the solution as . . .</p>
<p><img src='http://s0.wp.com/latex.php?latex=%5Cbegin%7Bpmatrix%7DG%28n%29%5C%5C+G%28n-1%29%5C%5C+H%28n%2B1%29%5C%5C+H%28n%29+%5Cend%7Bpmatrix%7D%3D%5Cbegin%7Bpmatrix%7Da%26b%26c%260%5C%5C+1%260%260%260%5C%5C+0%260%26d%26e%5C%5C+0%260%261%260+%5Cend%7Bpmatrix%7D%5E%7Bn-1%7D+%5Ctimes+%5Cbegin%7Bpmatrix%7DG%281%29%5C%5C+G%280%29%5C%5C+H%282%29%5C%5C+H%281%29%5Cend%7Bpmatrix%7D+&amp;bg=ffffff&amp;fg=666666&amp;s=0' alt='&#92;begin{pmatrix}G(n)&#92;&#92; G(n-1)&#92;&#92; H(n+1)&#92;&#92; H(n) &#92;end{pmatrix}=&#92;begin{pmatrix}a&amp;b&amp;c&amp;0&#92;&#92; 1&amp;0&amp;0&amp;0&#92;&#92; 0&amp;0&amp;d&amp;e&#92;&#92; 0&amp;0&amp;1&amp;0 &#92;end{pmatrix}^{n-1} &#92;times &#92;begin{pmatrix}G(1)&#92;&#92; G(0)&#92;&#92; H(2)&#92;&#92; H(1)&#92;end{pmatrix} ' title='&#92;begin{pmatrix}G(n)&#92;&#92; G(n-1)&#92;&#92; H(n+1)&#92;&#92; H(n) &#92;end{pmatrix}=&#92;begin{pmatrix}a&amp;b&amp;c&amp;0&#92;&#92; 1&amp;0&amp;0&amp;0&#92;&#92; 0&amp;0&amp;d&amp;e&#92;&#92; 0&amp;0&amp;1&amp;0 &#92;end{pmatrix}^{n-1} &#92;times &#92;begin{pmatrix}G(1)&#92;&#92; G(0)&#92;&#92; H(2)&#92;&#92; H(1)&#92;end{pmatrix} ' class='latex' /></p>
<h3>TYPE 4 : Ohhh !</h3>
<p>The final hurdle can come in the name of a constant. If we add a constant C to the above recurrence we get -</p>
<p><img src='http://s0.wp.com/latex.php?latex=G%28n%29+%3D+a+.+G%28n-1%29+%2B+b+.+G%28n-2%29+%2B+c+.+H%28n%29+%2B+C%5C%5C+%5C%5C+and+%5C%5C+%5C%5C+H%28n%29%3D+d+.+H%28n-1%29+%2B+e+.+H%28n-2%29+&amp;bg=ffffff&amp;fg=666666&amp;s=0' alt='G(n) = a . G(n-1) + b . G(n-2) + c . H(n) + C&#92;&#92; &#92;&#92; and &#92;&#92; &#92;&#92; H(n)= d . H(n-1) + e . H(n-2) ' title='G(n) = a . G(n-1) + b . G(n-2) + c . H(n) + C&#92;&#92; &#92;&#92; and &#92;&#92; &#92;&#92; H(n)= d . H(n-1) + e . H(n-2) ' class='latex' /></p>
<p>But to tell you the truth, its not that difficult if your concepts are clean. Now there is another additional state to hold the information about C. The solution will look like -</p>
<p><img src='http://s0.wp.com/latex.php?latex=%5Cbegin%7Bpmatrix%7DG%28n%29%5C%5C+G%28n-1%29%5C%5C+H%28n%2B1%29%5C%5C+H%28n%29%5C%5C+C+%5Cend%7Bpmatrix%7D%3D%5Cbegin%7Bpmatrix%7Da%26b%26c%260%261%5C%5C+1%260%260%260%260%5C%5C+0%260%26d%26e%260%5C%5C+0%260%261%260%260%5C%5C+0%260%260%260%261++%5Cend%7Bpmatrix%7D%5E%7Bn-1%7D+%5Ctimes+%5Cbegin%7Bpmatrix%7DG%281%29%5C%5C+G%280%29%5C%5C+H%282%29%5C%5C+H%281%29%5C%5C+C%5Cend%7Bpmatrix%7D+&amp;bg=ffffff&amp;fg=666666&amp;s=0' alt='&#92;begin{pmatrix}G(n)&#92;&#92; G(n-1)&#92;&#92; H(n+1)&#92;&#92; H(n)&#92;&#92; C &#92;end{pmatrix}=&#92;begin{pmatrix}a&amp;b&amp;c&amp;0&amp;1&#92;&#92; 1&amp;0&amp;0&amp;0&amp;0&#92;&#92; 0&amp;0&amp;d&amp;e&amp;0&#92;&#92; 0&amp;0&amp;1&amp;0&amp;0&#92;&#92; 0&amp;0&amp;0&amp;0&amp;1  &#92;end{pmatrix}^{n-1} &#92;times &#92;begin{pmatrix}G(1)&#92;&#92; G(0)&#92;&#92; H(2)&#92;&#92; H(1)&#92;&#92; C&#92;end{pmatrix} ' title='&#92;begin{pmatrix}G(n)&#92;&#92; G(n-1)&#92;&#92; H(n+1)&#92;&#92; H(n)&#92;&#92; C &#92;end{pmatrix}=&#92;begin{pmatrix}a&amp;b&amp;c&amp;0&amp;1&#92;&#92; 1&amp;0&amp;0&amp;0&amp;0&#92;&#92; 0&amp;0&amp;d&amp;e&amp;0&#92;&#92; 0&amp;0&amp;1&amp;0&amp;0&#92;&#92; 0&amp;0&amp;0&amp;0&amp;1  &#92;end{pmatrix}^{n-1} &#92;times &#92;begin{pmatrix}G(1)&#92;&#92; G(0)&#92;&#92; H(2)&#92;&#92; H(1)&#92;&#92; C&#92;end{pmatrix} ' class='latex' /></p>
<p>I hope this post lived up to your expectations and I hope it was worth the wait <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> . Please feel free to post comments/corrections/improvements to this post to make it really useful.<br />
<!-- Here Simplest is 0 at the beginning ! -&gt;--></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codeoverflow.wordpress.com/139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codeoverflow.wordpress.com/139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codeoverflow.wordpress.com/139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codeoverflow.wordpress.com/139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codeoverflow.wordpress.com/139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codeoverflow.wordpress.com/139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codeoverflow.wordpress.com/139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codeoverflow.wordpress.com/139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codeoverflow.wordpress.com/139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codeoverflow.wordpress.com/139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codeoverflow.wordpress.com/139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codeoverflow.wordpress.com/139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codeoverflow.wordpress.com/139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codeoverflow.wordpress.com/139/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeoverflow.wordpress.com&amp;blog=17915630&amp;post=139&amp;subd=codeoverflow&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codeoverflow.wordpress.com/2011/05/23/linear-recurrences/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/bb17aa8ea5a28152343e1c1b07a2467c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ashagrwal</media:title>
		</media:content>
	</item>
		<item>
		<title>Return to Roots: Tree 101</title>
		<link>http://codeoverflow.wordpress.com/2011/03/23/return-to-roots-tree-101/</link>
		<comments>http://codeoverflow.wordpress.com/2011/03/23/return-to-roots-tree-101/#comments</comments>
		<pubDate>Wed, 23 Mar 2011 13:20:24 +0000</pubDate>
		<dc:creator>SwitchCase</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[binary search tree]]></category>
		<category><![CDATA[binary tree]]></category>
		<category><![CDATA[bst]]></category>
		<category><![CDATA[inorder traversal]]></category>
		<category><![CDATA[insert]]></category>
		<category><![CDATA[iterative inorder traversal]]></category>
		<category><![CDATA[morris inorder traversal]]></category>
		<category><![CDATA[postorder traversal]]></category>
		<category><![CDATA[preorder traversal]]></category>
		<category><![CDATA[traversal]]></category>
		<category><![CDATA[Tree]]></category>
		<category><![CDATA[tree traversal]]></category>

		<guid isPermaLink="false">http://codeoverflow.wordpress.com/?p=129</guid>
		<description><![CDATA[What is a Tree : Tree is a heirarchial arrangement of nodes. From the literal meaning of Tree we know that it has root, branches, fruits and leaves. Well, in Algorithms also, we have a root &#8211; which is the origin of the tree. We have branches which connect to smaller trees and we have <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeoverflow.wordpress.com&amp;blog=17915630&amp;post=129&amp;subd=codeoverflow&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>What is a Tree :</strong></p>
<p>Tree is a heirarchial arrangement of nodes. From the literal meaning of Tree we know that it has  root, branches, fruits and leaves. Well, in Algorithms also, we have a root &#8211; which is the origin of the tree. We have branches which connect to smaller trees and we have leaves, which do not have outgoing branches. And as far as the fruits are concern &#8211; depending on the complexity of operations that can be perform, we may label the fruits as sweet and sour !</p>
<p>The simplest tree would be a node which branches to exactly one other node, or in other words &#8211; a singly Link List. If every node branches to its child and also to its parent, we have a doubly link list. But in this post, we are not going to discuss these.</p>
<p>The next level of trees would be &#8211; where a single node may branch out to a maximum of two other nodes. Such a tree is call a binary tree. Binary trees are some of the most widely us datastructures in computers and we are going to discuss them in a series of posts. So lets begin.</p>
<p>One of the most important things to do is : Create a tree.<br />
So what is it that we ne to create one. We will ne to represent the nodes and the links between nodes. And since we ne to connect to a maximum of two nodes, we will have two branches. We shall call these branches &#8211; left and right. Also, it will store some data in it. Our tree will be us to just store integers. </p>
<p>We will use the following structure to create it. FYI, everything here is in C++ and not C.<br />
<pre class="brush: cpp;">
struct NODE {
    int data;
    NODE *left;
    NODE *right;
};
</pre><br />
Now whenever we ne to insert a node, we ne to make sure that there is a fix position at which the node will be insert given its value (Data in the node). Let us follow a simple strategy.<br />
We will insert a node to the left of a &#8216;Parent node&#8217;, if its value is lesser than the value of the Parent, otherwise to the right. The binary trees which use such a strategy are call Binary Search Trees.</p>
<p>The obvious advantage of such a strategy is that we can search for elements in the tree in O(h) time, where h is the height of the tree. Do note that, in general,  h does not equal logN. If we could actually have a tree where the height is inde logN, we would call such trees as Balanc Binary Search Trees.</p>
<p>Alright then, lets get our hands dirty with a code that will create the tree for us. The function insert takes as input the root of the tree and the value to be insert and returns the node which contains the data.</p>
<p><pre class="brush: cpp;">
NODE * insert(NODE *root, int data) {
    if(root==NULL) {
        root=(NODE*)malloc(sizeof(NODE));
        root-&gt;left=root-&gt;right=NULL;
        root-&gt;data=data;
        return root;
    }
    else {
        while(root!=NULL) {
            if(root-&gt;data&gt;data) {
                if(root-&gt;left!=NULL) root=root-&gt;left;
                else break;
            }
            else {
                if(root-&gt;right!=NULL) root=root-&gt;right;
                else break;   
            }
        }
        NODE *new_node=new NODE;
        new_node-&gt;data=data;
        new_node-&gt;left=new_node-&gt;right=NULL;
        if(root-&gt;data &gt; data) {
            root-&gt;left=new_node;
        }
        else root-&gt;right=new_node;
        return new_node;
    }
}
</pre></p>
<p>Another very useful and important property when using the above strategy is, that the INORDER traversal is sort! </p>
<p>Lets backup a bit. What are Traversals. It is like visiting many homes using the roads which connect them. Only that, the homes here are the NODEs and the roads are the links between each node. </p>
<p>There are many traversals but the three us very often are &#8211; PreOrder, InOrder and PostOrder.</p>
<p>In PreOrder, you print the current node and then visit its left and then its right children, recursively.<br />
In InOrder, you first visit the left child, once you have return, you print the current value and then visit the right child.<br />
In PostOrder, you visit both your children and then print the current value.</p>
<p>Here is the code snippet for the InOrder traversal (recursive version).<br />
<pre class="brush: cpp;">
void inorder(NODE *root) {
    if(root!=NULL) {
        inorder(root-&gt;left);
        printf(&quot;%d &quot;,root-&gt;data);
        inorder(root-&gt;right);
    }
}
</pre><br />
You could write an iterative version, where you would simulate the operations in a system stack, using your own stack. The obvious advantage is that you would be saving space (since you would now push as many values as the system would for a function call.)</p>
<p>However, there exists a really beautiful iterative version which does not use a stack. It assumes that two pointers can be check for equality. It is bas on thread trees and it was first written in 1979	by Morris and hence the name!</p>
<p><strong>How does it work</strong>. </p>
<p>The only reason we ne a stack is so that we can do the &#8220;RETURN&#8221; from child nodes to parent nodes. This return is ne only from one node really. Consider a 5 node tree.<br />
<pre class="brush: cpp;">
                                      20
                                    /     \
                                   /       \
                                 10        30
                                /   \     
                               /     \
                             5       15
</pre><br />
Now our stack would work like this.<br />
<code><br />
1. Push 20.<br />
2. Push 10.<br />
3. Push 5.<br />
4. Pop 5 and print 5.<br />
5. Pop 10 and print 10.<br />
6. Push 15.<br />
7. Pop 15 and print 15.<br />
8. Pop 20 and print 20.<br />
9. Push 30.<br />
10. Pop 30 and print 30.<br />
</code></p>
<p>If I write a non-resursive and non-stack version, my greatest headache would be to go to 20 from 15 (statements 7-8). So we need to link 15 and 20 so that we can go to 20 without problems. But that would mean that we are modifying the tree. Well, we could do it in two steps. First we link the two and in the next step once we have printed 20, we can destroy that link.<br />
<pre class="brush: cpp;">
                                        20
                                      / | \
                                     /  |  \
                                   9    |   30
                                  /   \ |   
                                 /     \|
                               5       15
</pre><br />
And thus we have the following -</p>
<p>1. SET current as root.<br />
2. if current is not null do -<br />
2.a. if current has no left child, print current , set current as right child and REPEAT 2.<br />
2.b. else goto the rightmost child of current&#8217;s left child.<br />
	2.b.a. If this is NULL, then link it to current and set current as left child of current and REPEAT 2.<br />
	2.b.b. else set the right child to NULL. Print Current. Set current as Current&#8217;s right child . REPEAT 2.</p>
<p>As a pseudocode we may write it as -<br />
<pre class="brush: cpp;">
Morris-InOrder ( root )
current = root
while current != NULL do
	if LEFT(current) == NULL then
	   print current
	   current=RIGHT(current)
	else do
	   // set pre to left child of current
	   pre=LEFT(current)
	   // find rightmost child of the left child of current
	   while (RIGHT(pre) != NULL  and RIGHT(pre) != current) do
	       pre=RIGHT(pre)
	    //if thus is null, link it to current and set current's left as current
	    if RIGHT(pre) == NULL then
	       RIGHT(pre)=current
	       current=LEFT(current)
	    // else unlink it, print current and set right child of current as current
	    else do
	       RIGHT(pre)=NULL
	       print current
	       current=RIGHT(current)
</pre><br />
Looks nice aah. Let&#8217;s just write the code.</p>
<p><pre class="brush: cpp;">
void MorrisInorder(NODE *root) {
    NODE* current,*pre;
    current=root;
    while(current!=NULL) {
        if(current-&gt;left==NULL) {
            printf(&quot;%d &quot;,current-&gt;data);
            current=current-&gt;right;
        }
        else {
            pre=current-&gt;left;
            while(pre-&gt;right != NULL &amp;&amp; pre-&gt;right !=current) 
                pre=pre-&gt;right;
            if(pre-&gt;right==NULL) {
                pre-&gt;right=current;
                current=current-&gt;left;
            }
            else {
                pre-&gt;right=NULL;
                printf(&quot;%d &quot;,current-&gt;data);
                current=current-&gt;right;
            }
        }
    }
}
</pre></p>
<p>Now, lets talk about the fruits! </p>
<p>Insert happens in O(h) time. Each of the traversals (recursive and iterative versions using stack) are in O(N) time and O(N) space (system stack or normal stack). </p>
<p>Morris Inorder runs in O(NlogN) time and O(1) space. One could say that it is slower which is true, but the fact that it does not use additional space can be a huge boost in situations where you are low on system memory!</p>
<p>The entire code is available on :<a href="http://pastebin.com/v9uf1CNR">PASTEBIN</a><br />
I hope you gathered all that info well! I will post a Tree 102, in which I shall discuss the delete operation and talk more about balanced trees!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codeoverflow.wordpress.com/129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codeoverflow.wordpress.com/129/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codeoverflow.wordpress.com/129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codeoverflow.wordpress.com/129/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codeoverflow.wordpress.com/129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codeoverflow.wordpress.com/129/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codeoverflow.wordpress.com/129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codeoverflow.wordpress.com/129/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codeoverflow.wordpress.com/129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codeoverflow.wordpress.com/129/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codeoverflow.wordpress.com/129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codeoverflow.wordpress.com/129/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codeoverflow.wordpress.com/129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codeoverflow.wordpress.com/129/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeoverflow.wordpress.com&amp;blog=17915630&amp;post=129&amp;subd=codeoverflow&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codeoverflow.wordpress.com/2011/03/23/return-to-roots-tree-101/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/bb17aa8ea5a28152343e1c1b07a2467c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ashagrwal</media:title>
		</media:content>
	</item>
		<item>
		<title>Thou art Debugger</title>
		<link>http://codeoverflow.wordpress.com/2011/03/13/thou-art-debugger/</link>
		<comments>http://codeoverflow.wordpress.com/2011/03/13/thou-art-debugger/#comments</comments>
		<pubDate>Sun, 13 Mar 2011 08:00:19 +0000</pubDate>
		<dc:creator>SwitchCase</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Random]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[breakpoints]]></category>
		<category><![CDATA[CPU registers]]></category>
		<category><![CDATA[Debug]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[harware breakpoints]]></category>
		<category><![CDATA[how debuggers work]]></category>
		<category><![CDATA[memory breakpoints]]></category>
		<category><![CDATA[soft breakpoints]]></category>
		<category><![CDATA[working of debuggers]]></category>

		<guid isPermaLink="false">http://codeoverflow.wordpress.com/?p=117</guid>
		<description><![CDATA[I have been a big fan of Visual Studio. It is an amazing IDE. It can be used to develop anything from a CLI to GUI and from Mobile Apps to Web Apps. But I have never really tried all that and that isn&#8217;t the reason why I liked it so much. As a starter, <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeoverflow.wordpress.com&amp;blog=17915630&amp;post=117&amp;subd=codeoverflow&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I have been a big fan of Visual Studio. It is an amazing IDE. It can be used to develop anything from a CLI to GUI and from Mobile Apps to Web Apps. But I have never really tried all that and that isn&#8217;t the reason why I liked it so much. As a starter, it can be very difficult to discover a bug in your program. You safely assume you have written what you wanted to write. But in reality that happens very rarely. Often, we miss a little small thing here and there and that creates havoc. The one thing that caught my eye as a young programmer was the Debugging features of VS. Gosh, its amazing.<br />
In this article, I will explain how Debuggers debug!.</p>
<p>Firstly, we will need to learn a bit about CPU registers. We will concentrate on the x86 architecture. If you have ever written code in x86 Assembly, then you would have heard about them. But let me just walk you through the functions of these registers.</p>
<p>CPU registers are just memory that the CPU can use to store data. But, it is the fastest accessible memory for the CPU. Ideally you would like to keep everything in it. Unfortunately, it is damn expensive and so a trade-off is done on the pricing and performance. Though there are 32 registers, the most commonly used ones(9 to be precise) for the purpose of executing instuctions are &#8211; </p>
<p><strong>EAX</strong> : Accumulator : used to store. Used during add/sub/multiplication. Mult/Div cannot be done elsewehere except in EAX. Also used to store return values.<br />
<strong>EDX</strong> : storage register Used in conjuction to EAX. It is like a side-kick.<br />
<strong>ECX</strong>: count register: Used in looping. However, there is an interesting thing about it. It always counts downwards and not upwards.<br />
for ex:<br />
 <font face="Monospace"><em>int a=100;<br />
int b=0;<br />
while(b&lt;a)b++;</em></font></p>
<p>Then ECX will begin from 100 and not 0 and move to 99,98 … !<br />
<strong>ESI</strong> : source index for data operations and holds location of input stream.(READING)<br />
<strong>EDI</strong> : points to location where the result is stored of a data operation  destination index. (WRITING)<br />
<strong>ESP</strong> : Stack pointer<br />
<strong>EBP</strong>: Base pointer<br />
<strong>EBX</strong>: not designed for anything specific . can be used for extra storage.<br />
<strong>EIP</strong> : Current instruction being executed.</p>
<p>Now that we understand this, lets see how a debugger works!<br />
Depending on the type of breakpoint, one of the following happens :</p>
<p><strong>Soft Breakpoint :</strong><br />
Let us assume we need to execute this instruction :<br />
<font face="Monospace"><em>mov %eax,%ebx</em></font></p>
<p>And this is at location 0&#215;44332211, and the 2 byte opcode for this is 0x8BC3. Hence what we will see is :<br />
<font face="Monospace"><em>0&#215;44332211 0x8BC3 mov %eax,%ebx</em></font></p>
<p>Now when we create a soft breakpoint at this instruction what the debugger does is &#8211; it takes the first byte (8B in this case) and replaces it with 0xCC.<br />
So now, the opcode actually looks like &#8211; 0x<strong>CC</strong>C3. This is the opcode for INT 3 interrupt. INT 3 is used to halt the execution. Now when the CPU is happily executing everything till this one and suddenly sees the 0xCC it knows it has to stop(it may not really like it but &#8211; Rules are rules <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  ).  It then raises the INT 3 interrupt which the debugger will trap. It then checks the EIP register and sees if this intruction is actually in its list of breakpoints (just in case the program itself has a INT 3 inside it). If it is present, it will replace the first byte with the correct value (8B in this case) and then program execution can continue.</p>
<p>There are two kinds of soft breakpoint: <strong>One shot</strong> &#8211; Where the breakpoint occurs only once and after that the debugger removes the instruction from its list; and <strong>Persistent</strong> &#8211; where it keeps recurring. The debugger would replace the first byte with the correct byte but when execution is resumed, it will once again replace it with 0xCC and not remove it from its list.</p>
<p>Soft breakpoints have one caveat though.When we make a soft breakpoint it changes the software/program’s CRC (cyclic redundancy check) check sum. A CRC is a type of function which tells whether there has been any change or not. It is like a hash function and can be applied to memory/files etc.,. It compares against a known value and if the checksum fails, the CRC fails. This can be used to prevent Soft breakpoints like in malwares where if the CRC fails, the malware kills itself. To get around this we use Hardware breakpoints!</p>
<p><strong>Hardware Breakpoints &#8211; </strong><br />
Though hardware breakpoints cannot be applied at everything, it is still very useful. Recall, the I said there are 32 registers. I introduced 9 in the previous section, let me add another 8 to that list. These eight &#8211; DR0 to DR7 are debug registers. DR0 &#8211; DR3 store the address of the breakpoints and thus we can have only 4 hardware breakpoints (Ouch!). DR4 and DR5 are reserved. DR6 is the status register which determines the type of debugging event once it is hit and DR7 is ON/OFF switch for hardware breakpoints and also stores different conditions like -<br />
   1. Break when an instruction is executed at a particular address.<br />
   2. Break when data is written to an address.<br />
   3. Break on reads or writes to an address but not execution.</p>
<p>As you can guess, you can only break 4 bytes of memory with hardware breakpoints but nonetheless they are very useful tools for reverse engineers. For creating hardware breakpoints, you can use hbreak command inside gdb.( <a href="http://www.ofb.net/gnu/gdb/gdb_29.html">More info</a> ).</p>
<p><strong>Memory breakpoints.</strong><br />
These arent really breakpoints. It is more like setting permissions on a section of memory or on an entire page, something similar to file permissions. When we set a particular permission, if any instruction tries to do something outside of these permissions on that memory, then a break occurs. The permissions available are &#8211; Page Execution (enables exec but throws access violation on read/write) , Page Read ( allows only read), Page Write (only write), and Guard Page (one time exception after which the page returns to its original status).  Like in files, we can use combination of these to set permissions. In gdb, to break on write use watch, rwatch will break on read and awatch will break on read/write.</p>
<p>I hope you now have a better understanding of how debuggers work. You may feel this as being unnecessary info, but trust me it helps to know how things work for better usage.</p>
<p>I would like to thank all Source of knowledge &#8211; the World Wide Web. Please free to send me corrections/suggestions/criticism.<br />
Adios!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codeoverflow.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codeoverflow.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codeoverflow.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codeoverflow.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codeoverflow.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codeoverflow.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codeoverflow.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codeoverflow.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codeoverflow.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codeoverflow.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codeoverflow.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codeoverflow.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codeoverflow.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codeoverflow.wordpress.com/117/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeoverflow.wordpress.com&amp;blog=17915630&amp;post=117&amp;subd=codeoverflow&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codeoverflow.wordpress.com/2011/03/13/thou-art-debugger/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/bb17aa8ea5a28152343e1c1b07a2467c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ashagrwal</media:title>
		</media:content>
	</item>
		<item>
		<title>Quick-Short</title>
		<link>http://codeoverflow.wordpress.com/2011/01/17/quick-short/</link>
		<comments>http://codeoverflow.wordpress.com/2011/01/17/quick-short/#comments</comments>
		<pubDate>Mon, 17 Jan 2011 09:09:43 +0000</pubDate>
		<dc:creator>SwitchCase</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Complexity]]></category>
		<category><![CDATA[Jon Bentley]]></category>
		<category><![CDATA[Quick Sort]]></category>
		<category><![CDATA[Sorting]]></category>
		<category><![CDATA[Three Beautiful Quicksort]]></category>

		<guid isPermaLink="false">http://codeoverflow.wordpress.com/?p=89</guid>
		<description><![CDATA[Hi, The cheapest, fastest and most reliable components of a computer system are those that aren&#8217;t there. &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; -Gordon Bell I am back with a new post. And this time its about one of my favourite algorithms (Yes, as a geek I am allowed to have fav algos ) &#8211; Quick Sort ! Whats so <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeoverflow.wordpress.com&amp;blog=17915630&amp;post=89&amp;subd=codeoverflow&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Hi,</p>
<blockquote><p><strong><em><br />
The cheapest, fastest and most reliable components of a computer system are those that aren&#8217;t there.<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; -Gordon Bell</em></strong><em></em></p></blockquote>
<p>I am back with a new post. And this time its about one of my favourite algorithms (Yes, as a geek I am allowed to have fav algos <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':-P' class='wp-smiley' />  ) &#8211; Quick Sort ! Whats so special about it &#8211; It is amazingly simple and very clearly complex. Quick sort can be implemented as horribly as follows -<br />
<pre class="brush: cpp;">

void quicksort(int *x,int l,int u)
{
	int i,j,t;
	if(l&gt;=u)return;
	t=x[l];
	i=l;
	j=u+1;
	for(;;)
	{
		do i++; while(i&lt;=u &amp;&amp; x[i]&lt;t);
		do j--;while(x[j]&gt;t );
		if(i&gt;j)break;
		swap(x[i],x[j]);
	}
	swap(x[l],x[j]);
	quicksort(x,l,j-1);
	quicksort(x,j+1,u);
}

</pre></p>
<p>or as simple as </p>
<p><pre class="brush: cpp;">

void quicksort(int *x,int l,int u)
{	
	int i,j,t;
	if(l&gt;=u)return;
	t=x[l];
	i=l;
	for(j=l+1;j&lt;=u;j++)
	{
		if(x[j]&lt;x[l])
			swap(x[++i],x[j]); 
	}
	swap(x[l],x[i]);
	quicksort(x,l,i-1);
	quicksort(x,i+1,u);	
}

</pre></p>
<p>But in this post, we are not going to see its looks but rather we are going to explore its performance (real beauty).<br />
Anyone who attended a class on &#8216;Algorithms and Data-structures&#8217; or had the pleasure of learning it on your own (like me) knows that Quick Sort runs in O(nlogn) expected average time. Its a known fact that for any given quick-sort (standard implementation) there exists a case which will ensure that it runs in O(n^2) time (even for the purely randomized version. If you don&#8217;t know about it, feel free to comment at the bottom and I will let the secret out <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':-P' class='wp-smiley' />  ) . </p>
<p>But what if I wanted to find the average expected time. I know there exists a mathematical derivation using Expectation and it shows that it is nlogn but what if I wanted to find out the exact number of comparisons made on the average. We are going to make an attempt on that. </p>
<p>Before we do that, we should take a minute to observe that there are two variables on which quicksort&#8217;s performance can be measured. One is the Number of SWAPS made and the second is the Number of Comparisons. We must select the variable which has the most impact in reducing its complexity. In this post I am using Comparisons over Swaps, Why? Simple because, the impact of a comparison is more than the impact of a Swap. How to prove it? Simple- Write a piece of CODE! (I will post the code a little later)</p>
<p>We will just add a new counter before the comparison inside the loop and when the sort exits, we will have the exact count of the comparisons made.</p>
<p><pre class="brush: cpp;">

void quicksort(int *x,int l,int u)
{	
	int i,j,t;
	if(l&gt;=u)return;
	t=x[l];
	i=l;
	for(j=l+1;j&lt;=u;j++)
	{
            cmp++;
		if(x[j]&lt;x[l])
			swap(x[++i],x[j]); 
	}
	swap(x[l],x[i]);
	quicksort(x,l,i-1);
	quicksort(x,i+1,u);	
}

</pre></p>
<p>A very basic optimization would be to add it outside the loop as shown.</p>
<p><pre class="brush: cpp;">

void quicksort(int *x,int l,int u)
{	
	int i,j,t;
	if(l&gt;=u)return;
	t=x[l];
	i=l;
    cmp+=u-l;
	for(j=l+1;j&lt;=u;j++)
	{
		if(x[j]&lt;x[l])
			swap(x[++i],x[j]); 
	}
	swap(x[l],x[i]);
	quicksort(x,l,i-1);
	quicksort(x,i+1,u);	
}
</pre></p>
<p>It is still slow and I want to speed it up. Is there any way I can get rid of that for loop. Actually, YES. I can remove it clearly. I know you are throwing away your thinking hat saying that -&#8221; WHAT WILL YOU SORT ? AND IF YOU AREN&#8217;T SORTING ANYTHING WHATS THE POINT ?&#8221; Well, you are right. I am not interested in sorting. I am only interested in estimating the time it will take to run on average. To do this, I don&#8217;t need to sort any array, I just need to simulate it and to simulate it quicker, I will remove the for loop and everything associated with it.<br />
Now our simulator code looks like this. I have also removed the two variables and replaced it with the length I want to partition.</p>
<p><pre class="brush: cpp;">

int quicksort_count(int L)
{
	int m;
	if(n&lt;=1)return 0;
	m=l+(rand()%L);
	return n-1 + quicksort_count(m-1) + quicksort_count(L-m-1);
}
</pre><br />
But, if we want to find the true average, we need to do this for every possible m that may be chosen. Hence we can modify our code to.</p>
<p><pre class="brush: cpp;">
double quicksort_avg(int L)
{
	if(n&lt;=0)return 0;
	double sum=0.0;
	for(int m=1;m&lt;=L;m++)
		sum+=L-1 + quicksort_avg(m-1) + quicksort_avg(L-m);
	return sum/L;
}
</pre></p>
<p>We can improve its runtime by using Dynamic Programming. We could use the Top-Down approach where we store the values that were previously computed in an array and look it up or we could do Bottom-Up and compute the values in increasing order.</p>
<p><pre class="brush: cpp;">

double quicksort_avg(int L)
{
    double dp[L+5];//5 is just taken for safety !
    dp[0]=0;
	for(int n=1;n&lt;=L;n++)
	{  
        double sum=0.0;
	    for(int m=1;m&lt;=n;m++)
	       	sum+=n-1 + dp[m-1] + dp[n-m];
	     dp[n]=sum/n;  	
    }   
	return dp[L];
}
</pre></p>
<p>I am still not happy. It is using O(N^2) time which I obviously do not like.  It may seem like its impossible to reduce it but in reality that is not the case. For example, if n=5, then the look ups would be : </p>
<blockquote><p>0 and 5-1<br />
1 and 5-2<br />
2 and 5-3<br />
3 and 5-4<br />
4 and 5-5.</p></blockquote>
<p> As you can see, I am looking up the same elements twice !<br />
So, I could remove the two lookups and instead multiply it by 2. Also, I can remove the n-1 added every time in the loop (n times to be accurate) and then I divide it by n, leaving me n-1. With those changes, I can convert it to O(N) time.</p>
<p><pre class="brush: cpp;">
double quicksort_avg(int L)
{
    double dp[L+5],sum=0;
    dp[0]=0;
    for(int n=1;n&lt;=L;n++)
    {
        sum+=2*dp[n-1];
        dp[n]=n-1  + sum/n;   
    }
    return dp[L];
}
</pre></p>
<p>Even now, I am not happy. ( Its impossible to make me happy, right ?). We can actually improve on the O(N) space, since we are only looking at the previous state. Now, our final piece looks like :</p>
<p><pre class="brush: cpp;">
double quicksort_avg(int L)
{
    double dp,sum=0;
    dp=0;
    for(int n=1;n&lt;=L;n++)
    {
        sum+=2*dp;
        dp=n-1 + sum/n;   
    }
    return dp;
}

</pre></p>
<p>Beautiful isn&#8217;t it. In one for-loop using 2 variables, I can actually find out the average comparions made by  quicksort for a given length of numbers. </p>
<p>What I (rather Jon Bentley) is trying to show is that &#8211; sometimes and almost always we can add functionality by actually removing code! Though this was a pretty small example (and a beautiful example), it seems to explain the idea pretty well.</p>
<p>Do watch the video.</p>
<p><strong>The original video: Three Beautiful QuickSorts</strong></p>
<span style='text-align:center;display:block;'><object width='400' height='330' type='application/x-shockwave-flash' data='http://video.google.com/googleplayer.swf?docId=-1031789501179533828'><param name='allowScriptAccess' value='never' /><param name='movie' value='http://video.google.com/googleplayer.swf?docId=-1031789501179533828'/><param name='quality' value='best'/><param name='bgcolor' value='#ffffff' /><param name='scale' value='noScale' /><param name='wmode' value='opaque' /></object></span>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codeoverflow.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codeoverflow.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codeoverflow.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codeoverflow.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codeoverflow.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codeoverflow.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codeoverflow.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codeoverflow.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codeoverflow.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codeoverflow.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codeoverflow.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codeoverflow.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codeoverflow.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codeoverflow.wordpress.com/89/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeoverflow.wordpress.com&amp;blog=17915630&amp;post=89&amp;subd=codeoverflow&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codeoverflow.wordpress.com/2011/01/17/quick-short/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/bb17aa8ea5a28152343e1c1b07a2467c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ashagrwal</media:title>
		</media:content>
	</item>
		<item>
		<title>BrainFUCK-ed</title>
		<link>http://codeoverflow.wordpress.com/2010/12/26/brainfuck-ed/</link>
		<comments>http://codeoverflow.wordpress.com/2010/12/26/brainfuck-ed/#comments</comments>
		<pubDate>Sun, 26 Dec 2010 08:06:10 +0000</pubDate>
		<dc:creator>SwitchCase</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Random]]></category>
		<category><![CDATA[brainf*k]]></category>
		<category><![CDATA[brainfcuk]]></category>
		<category><![CDATA[brainfuck]]></category>
		<category><![CDATA[Esolang]]></category>
		<category><![CDATA[fibonacci]]></category>

		<guid isPermaLink="false">http://codeoverflow.wordpress.com/?p=71</guid>
		<description><![CDATA[If you are offended by the title, then please SKIP! So, you were caught in the BrainFuck bubble as well. Isn&#8217;t it one of the coolest esolangs out there! You might argue &#8211; Whats the use of this language. It can&#8217;t be used for any REAL software development. Maybe. But as a programmer, it can <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeoverflow.wordpress.com&amp;blog=17915630&amp;post=71&amp;subd=codeoverflow&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>If you are offended by the title, then please SKIP! So, you were caught in the BrainFuck bubble as well. Isn&#8217;t it one of the coolest esolangs out there! You might argue &#8211; Whats the use of this language. It can&#8217;t be used for any REAL software development. Maybe. But as a programmer, it can really strech your boundaries. How? Lets say in C, you had to write a program to print the first five fibonacci numbers (using the logic and not just printing it out), you would code it with your toes. I would too. But think of it in BrainFUCK and you will understand why Urban Muller named it so appropriately.</p>
<p>Here is the <a href="http://en.wikipedia.org/wiki/Brainfuck">Wikilink</a> for it so that you can see the basics of the languange. </p>
<p>In a C version of it, you will need 3 variables &#8211; to store the previous value and current value, and one temporary. One more to make sure you only print 5 and not any more , making our count 4 !<br />
Lets look at the code now :<br />
<pre class="brush: cpp;">
int main()
{
	int prev=1,curr=1,temp,count;
	for(count=0;count&lt;5;count++)
	{
		printf(&quot;%d &quot;,curr);
		temp=curr;
		curr=prev+curr;
		prev=temp;

	}
}
</pre><br />
That was quick.<br />
But even a simple program like this could make you think very hard in BrainFuck. Its fun to know that you have to think to write simpler programs. It makes my blood rush with just the thought of it.</p>
<p>So here goes !<br />
We only have 8 instructions, out of which we will use 7 (since we are not reading anything from the stdin).<br />
You have to think through absolutely every single thing before you so even put a &#8216;.&#8217; (dot) on the code editor (quite literally).<br />
We need to print SPACE, so we need 32(ASCII of SPACE) in the memory somewhere!.<br />
We need to print number (for simplicities sake, ONE digit numbers) so we need to make sure we have the ASCII values of it, in memory (ASCII of 0 is 48, 1 is 49 and so on..).<br />
If you look at the C code, we will need keep count of the number of items we have remaining to print. And then we need two locations to store previous and current values of the sequence. A very important thing to remember is that all memory is initialized to 0 at the start and we are relying on this for it to work. Also, the looping statements compare the memory location currently being referred (where your current pointer is) to against 0 and if it is true it breaks otherwise loops.</p>
<p>Writing a simple pseudocode (in terms of only Brainf*k) :<br />
<pre class="brush: cpp;">
Initialize a location A to 32
Initialize a location B to 48
Initialize a location C to 5
Initialize a location D and E to 1.
Set current Location to C.
Start a Loop
	Add B to E and F.
	Print E.
	Subtract B from E
	Add D to E and F
	Copy E to D 
	Copy F to E
	Reduce C by 1 and Set it as the current location
End Loop
</pre><br />
Basically, it was very easy to write this pseudocode. The issue with Braninf*k is that it does not have a COPY instruction for us to use, and so we need to use a looping statement to copy data. But the problem is that to ensure that the loop is executed the correct number of times, we will need to destroy the original value. To get around this, we always update two locations (one where we need it to be copied and the other a temporary!) and then we copy back from the temporary which also destroys it!</p>
<p>Also the A,B,C,D,E and F are all contiguous in memory and so I am using a[0],a[1]&#8230;a[6] to refer to them in the code !</p>
<p>Here is the final version. </p>
<p><pre class="brush: cpp;">
++++++++[&gt;++++&gt;++++++&lt;&lt;-]&gt;&gt;&gt;++++++&gt;+&gt;+&lt;&lt;-[&lt;[&gt;&gt;&gt;+&gt;+&lt;&lt;&lt;&lt;-]&gt;&gt;&gt;.&lt;&lt;&lt;&lt;.&gt;&gt;&gt;&gt;&gt;[&lt;-&lt;&lt;&lt;+&gt;&gt;&gt;&gt;-]&lt;[&gt;+&gt;+&lt;&lt;-]&lt;[&gt;&gt;&gt;+&lt;&lt;&lt;-]&gt;&gt;[&lt;&lt;+&gt;&gt;-]&gt;[&lt;&lt;+&gt;&gt;-]&lt;&lt;&lt;&lt;-]  
</pre></p>
<p>To make sense of it I have divided it into parts. Some parts have not been commented and are left as an exercise for you to figure out ( I know I am mean <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  ). </p>
<p><pre class="brush: cpp;">
++++++++[&gt;++++&gt;++++++&lt;&lt;-] //32 48
&gt;&gt;&gt;++++++ //6
&gt;+&gt;+&lt;&lt;- //Set first two values to 1 and reduce the number of terms to be printed to 5.
[
	&lt;[&gt;&gt;&gt;+&gt;+&lt;&lt;&lt;&lt;-]
	&gt;&gt;&gt;.//print the number
	&lt;&lt;&lt;&lt;.//print space
	&gt;&gt;&gt;&gt;&gt;[&lt;-&lt;&lt;&lt;+&gt;&gt;&gt;&gt;-]
	&lt;[&gt;+&gt;+&lt;&lt;-]
	&lt;[&gt;&gt;&gt;+&lt;&lt;&lt;-]
	&gt;&gt;[&lt;&lt;+&gt;&gt;-]//copy from a[6] to a[4]
	&gt;[&lt;&lt;+&gt;&gt;-]//copy from a[7] to a[5]
	&lt;&lt;&lt;&lt;-//decrement the value
]  
</pre></p>
<p>All right. Pretty cool huh! Well as a real mind-boggler you can try making it print N numbers (dont worry about printing it right, just print out the actual value encoded by ascii ). </p>
<p>You could use it to even encrypt messages in a really wierd way. Oh almost forgot. To run your Brainf*k programs use the following website. They have an online interpreter and a debugger of sorts too : <a href="http://www.brainfk.tk">www.brainfk.tk</a></p>
<p>I hope you liked your Christmas Present <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> .   Merry Christmas and a Happy New Year&#8230; Ho oh ho <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':-P' class='wp-smiley' /> </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codeoverflow.wordpress.com/71/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codeoverflow.wordpress.com/71/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codeoverflow.wordpress.com/71/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codeoverflow.wordpress.com/71/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codeoverflow.wordpress.com/71/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codeoverflow.wordpress.com/71/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codeoverflow.wordpress.com/71/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codeoverflow.wordpress.com/71/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codeoverflow.wordpress.com/71/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codeoverflow.wordpress.com/71/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codeoverflow.wordpress.com/71/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codeoverflow.wordpress.com/71/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codeoverflow.wordpress.com/71/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codeoverflow.wordpress.com/71/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeoverflow.wordpress.com&amp;blog=17915630&amp;post=71&amp;subd=codeoverflow&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codeoverflow.wordpress.com/2010/12/26/brainfuck-ed/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/bb17aa8ea5a28152343e1c1b07a2467c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ashagrwal</media:title>
		</media:content>
	</item>
		<item>
		<title>Naughty Null</title>
		<link>http://codeoverflow.wordpress.com/2010/12/23/naughty-null/</link>
		<comments>http://codeoverflow.wordpress.com/2010/12/23/naughty-null/#comments</comments>
		<pubDate>Thu, 23 Dec 2010 15:07:13 +0000</pubDate>
		<dc:creator>SwitchCase</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Random]]></category>
		<category><![CDATA[Djikstra]]></category>
		<category><![CDATA[Edsger Djikstra]]></category>
		<category><![CDATA[Hoare]]></category>
		<category><![CDATA[Null Reference]]></category>
		<category><![CDATA[Object]]></category>
		<category><![CDATA[pointer]]></category>
		<category><![CDATA[Record]]></category>

		<guid isPermaLink="false">http://codeoverflow.wordpress.com/?p=53</guid>
		<description><![CDATA[Hi, I am sorry it took me this long for the post. But to my fans (:P) I will be posting (hopefully) 2 more as promised in the next 2 days (actually nights). This Post is based entirely on Sir Anthony Hoare&#8217;s Lecture on &#8211; NULL REFERENCES &#8211; A BILLION DOLLAR MISTAKE If you have <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeoverflow.wordpress.com&amp;blog=17915630&amp;post=53&amp;subd=codeoverflow&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Hi, I am sorry it took me this long for the post. But to my fans (:P) I will be posting (hopefully) 2 more as promised in the next 2 days (actually nights).<br />
This Post is based entirely on Sir Anthony Hoare&#8217;s Lecture on &#8211; <strong>NULL REFERENCES &#8211; A BILLION DOLLAR MISTAKE</strong></p>
<blockquote><p>
If you have a null reference &#8211; every bachelor in the world would seem married, polyandrously!<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-Edsger Djikstra</p></blockquote>
<p><strong>What is a Null Reference : </strong> A Null reference is a pointer that points to a NULL (in C++).  For example,</p>
<p><pre class="brush: cpp;">
#include&lt;stdio.h&gt;
int main()
{
    char *cp=NULL;
    cp=(char*)(malloc(sizeof(char)*12);
    cp=&quot;HELLO THERE&quot;;
    printf(&quot;%s\n&quot;cp);
}
</pre></p>
<p>Here, in <em>Line 4</em> you have a Null Reference. Now you would wonder why that is a bad thing. In the context of this program, it isnt all that bad since it executes smoothly. But if you begin using complex source codes then you will have to be careful that you do no use/pass a NULL REFERENCE in/to a function. As this can lead to potential issues &#8211; sometimes almost impossible to detect !</p>
<p><strong><em>A HISTORY LESSON : </em></strong><br />
	Hoare&#8217;s first job was in the 60&#8242;s, as a programmer for a British Manufacturer &#8211; Elliots. After about 9 months, he was asked to design a new programming language ( Imagine this as your assignment at your first job !) While working on that, he found a book &#8211; Report on the International Algorithmic Language &#8211; ALGOL-60 (around 23 pages). He mostly wrote the new language around Algol 60 and left out complicated parts like if statements but later added them into it.
<p>
	In those days, code was written in Machine Language and it was easier to debug in machine language ( I never thought I would ever hear that!) than in high level languages because of now knowing the exact values in the 4096 bytes of memory. The principle involved was that &#8221; One should be able to tell the error by looking at the high level code alone&#8221;. And this was a real problem and people were a little nervous about the high level languages. But as the complexity went up, it was accepted eventually.</p>
<p>Now, Lets examine another piece of commonly used code -</p>
<p><pre class="brush: cpp;">
#include&lt;stdio.h&gt;
#define N 100
int main()
{
	int arr[N];
	int s=0;
	int k
	/*** SOME CODE TO DO SOME OPERATIONS ON ARRAYS ***/
	/*** SOME CODE THAT MODIFIES k***/
	
	while(s&lt;N)
        {
              printf(&quot;%d\n&quot;,arr[s]);
              s++;
        }
	if(k&gt;=0 &amp;&amp; k&lt;N)printf(&quot;K-th value is %d\n&quot;,arr[k]);
}
</pre></p>
<p>If we look at what we are doing in the code at <em> Line 10 and 11</em> &#8211; We are making sure that the subscript in within bounds. Thus we see that two checks(Upper Bound and Lower bound) are required to make sure this condition is satisfied. But this added to the time to run code (In those days the processors were really slow and things like if-s could take up a large amount of time !) and also to the size of the code.</p>
<p>A Question may come up &#8211; Is this a good thing to do? The Answer is YES. Languages like JAVA already implement it!</p>
<p>Hoare later on went on to become part of the team to design the successor of ALGOL &#8211; 60. He suggested that an Object/Record could be referenced by a pointer. But pointers in indirect memory can cause absolute havoc, because if you used a float as a pointer you could end up overwriting your own code! Thus, he took it for granted that the programmer must declare what data the pointer points to and it could be checked at compile time. He asked the customers &#8211; Whether they would like the Type checking removed once the code was tested ? They said No. The reason being that there are more chances of errors and issues popping up in a Live environment than in a test environment.</p>
<p>At that point, many people also used FORTRAN instead of ALGOL and Elliot wanted to sell it to them also. So they wrote a program which converted FORTRAN to ALGOL. It was a disaster, not because it compromised the speed but because &#8211; after converting it, it would come up with an entire essay of subscript errors.</p>
<p>Hoare invented the NULL REFERENCE but his friend Edsger Djikstra thought that it was a bad idea &#8211; If you have a null reference &#8211; every bachelor in the world would seem married, polyandrously &#8211; since every bachelor has the same wife &#8211; NULL but is still a bachelor ! </p>
<p>Hoare came up with a solution based on Discrimination of Objects belonging to the disjoint Union Class &#8211; A union between two sets with nothing in common! For eg, if we have a class Vehicle and subclasses &#8211; Cars and Bus. They both have an attribute Capacity but for a bus it refers to the passenger Capacity whereas for a car it refers to boot capacity. Thus it would discriminate based on bus or car and give you the corresponding capacity (by making a discriminating class.) Thus a pointer could point to a vehicle or to NULL.</p>
<p>Also, having NULL made it easy to initialize. If you didn&#8217;t do it this way, you could end up doing it in a really complex manner which could require a sub-language of its own. For eg, it is easy to design a data-structure without the NULL but almost impossible to design a circular structure without it! Hoare did not want to deal with that and hence NULL became a possible value for every pointer.</p>
<p>Thus in a way, it also influenced the way C was written. One of the greatest issues was the gets() function in C, which allowed buffer &#8211; overflow. If it had not been for it, the World would have been free of malwares !</p>
<p>If you asked me whether it was a Good choice or a bad choice to have a NULL reference &#8211; I would say that it was a good choice. Consider the amount of time I have saved thanks to the NULL pointer and the structures also owe some stability to the NULL Pointer. However, one must be very careful around it because it is very dificult to see that the pointer points to a NULL and it can be a cause for many a sleepless night!</p>
<p><a href="http://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare">See it yourself</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codeoverflow.wordpress.com/53/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codeoverflow.wordpress.com/53/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codeoverflow.wordpress.com/53/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codeoverflow.wordpress.com/53/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codeoverflow.wordpress.com/53/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codeoverflow.wordpress.com/53/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codeoverflow.wordpress.com/53/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codeoverflow.wordpress.com/53/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codeoverflow.wordpress.com/53/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codeoverflow.wordpress.com/53/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codeoverflow.wordpress.com/53/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codeoverflow.wordpress.com/53/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codeoverflow.wordpress.com/53/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codeoverflow.wordpress.com/53/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeoverflow.wordpress.com&amp;blog=17915630&amp;post=53&amp;subd=codeoverflow&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codeoverflow.wordpress.com/2010/12/23/naughty-null/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/bb17aa8ea5a28152343e1c1b07a2467c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ashagrwal</media:title>
		</media:content>
	</item>
		<item>
		<title>Binary Search Nightmares</title>
		<link>http://codeoverflow.wordpress.com/2010/11/23/binary-search-nightmares/</link>
		<comments>http://codeoverflow.wordpress.com/2010/11/23/binary-search-nightmares/#comments</comments>
		<pubDate>Tue, 23 Nov 2010 10:22:49 +0000</pubDate>
		<dc:creator>SwitchCase</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[overflow]]></category>
		<category><![CDATA[search]]></category>

		<guid isPermaLink="false">http://codeoverflow.wordpress.com/?p=18</guid>
		<description><![CDATA[Binary Search Nighmares : Oh yes, I&#8217;ve had nightmares about binary search. The worst kind. Now, you would tell me &#8211; What kinda geek are you ! I&#8217;ll answer &#8211; an honest Geek. Many people feel that the Binary Search is the easiest algorithms but in fact it is much more complex than some of the <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeoverflow.wordpress.com&amp;blog=17915630&amp;post=18&amp;subd=codeoverflow&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Binary Search Nighmares :</p>
<blockquote><p>Oh yes, I&#8217;ve had nightmares about binary search. The worst kind. Now, you would tell me &#8211; What kinda geek are you ! I&#8217;ll answer &#8211; an honest Geek. Many people feel that the Binary Search is the easiest algorithms but in fact it is much more complex than some of the other algorithms.</p></blockquote>
<p>To give you a brief background, I can write everything from a Quick Sort to Djikstra SSSP in over 4 programming languages without so much as blinking but when it comes to binary search &#8211; my heart begins to pound and my head begins to twirl. Why ? Because every line of that algorithm is just too simple that we (or maybe just me !) don&#8217;t pay close attention to it. You may not agree and I won&#8217;t blame you. Most programmers have used binary search to just do that &#8211; search. Not that I use it for something else. But just that the way you can apply binary search to an array of problems is amazing. And its only when you begin to apply it to others areas, you realize that you never really understood Binary Search !</p>
<p>Let me first show you the actual code :</p>
<p><pre class="brush: cpp;">
int binary_search(int *arr, int sizeOfArray,int search)
{
	lo=0;
	hi=sizeOfArray-1;
	while(lo&lt;=hi)
	{
			mid= lo + (hi-lo)/2;
			if(arr[mid]==search)
			{
				//ELEMENT FOUND
				return mid;
			}
			if(arr[mid]&lt;search)
				lo=mid+1;
			else hi=mid-1;
	}
	return -1;
}
//ELEMENT NOT FOUND
</pre></p>
<p>The algorithm is only ~10 lines, but each line is very important. Lets start with line 5: This is the condition that controls the looping. It is important to realize that if the element exists in the array, then the above condition can be anything that ensures continuous looping because on finding the element, we will break. But, if the item is not present in the array, then this condition is very important.</p>
<p>1. We are very easily tempted to write the value, lo&lt;hi instead of lo &lt;<strong>=</strong>hi, and I will show you why we shouldn&#8217;t give into that temptation.<br />
Consider the case :<code> 1, 3 4, 5, 10 ,12 14 </code> and we are looking for 10. The series of updates to lo,hi and mid are as follows.<br />
<code><br />
lo=0,hi=6,mid=3;<br />
lo=4,hi=6,mid=5;<br />
lo=4,hi=4,mid=4;</code></p>
<p>Now for the last loop, if we had not used the &#8216;=&#8217; condition, it would have broken from the loop without even finding.</p>
<p>2. Okay. Does the next line look like magic to you ? It is nothing but a better way of writing (lo+hi)/2. Now, why do I need that ? &#8211; To save me from the overflow. You see- (lo+hi) could easily overflow the integer range and result into some non-sensical data. Of course, it won&#8217;t happen in most cases as you cannot actually have an array the size of a 32 bit number, but still it is better to avoid it !</p>
<p>3. In most cases, you would write lo=mid, afterall that is what the leading text suggests but then why have I used mid+1 ?<br />
Consider the case : <code>0 2 5</code> and search for 3.<br />
<code>lo=0,hi=2,mid=1;<br />
lo=1,hi=2,mid=1;<br />
lo=1,hi=2,mid=1; </code></p>
<p>and it goes on forever !</p>
<p>For the same reason we use hi=mid-1.<br />
Now to prove why this is NOT wrong. Now, if the condition arr[mid] &lt;search is satisfied, it means that (mid+1)-th element is definitely larger that mid-th element. We have already checked with the mid-th element so we can move the lower bound to the element which is after that. Thus it does not hamper the algorithm in any way!</p>
<p>A very common problem employing binary search is , given a monotonically increasing/decreasing function F(x) find a value of x such that F(x)= VALUE. The domain of x is real numbers. To do this, we need to remember that the domain is really dense and so it is not possible to get a F(x) which is EXACTLY equal to VALUE, so we define a new function SATISFY(x,VALUE) which return true if for a given x, F(x) is within a satisfactory range of VALUE. Also, for this case, the condition to in the while loop is just the precision required on the return value.<br />
Thus,</p>
<p><pre class="brush: cpp;">
	double EPS= precision_required;
	double lo=lower_bound, hi=upper_bound;
	while( abs(lo-hi)&gt; EPS)
	{
		mid=lo+(hi-lo)/2.0;
		if(SATISFY(mid,VALUE)==true)
			hi=mid;
		else lo=mid;
	}
	// lo is the answer !!
</pre></p>
<p>Lastly, one usage of binary search ( give it a shot) :</p>
<blockquote><p>Given an array of N numbers (sorted) and given a search term- S, find the largest index i, such that the number at i, is smaller than S but larger than any other number smaller than S.</p>
<p>Eg: case: <code>1 2 2 2 3 4 5 7 7 8 8 9 </code>. and S= 8. Then the answer is 8, as the 8th number (0-indexed) = 7 is the largest of all numbers smaller than S, and 8 is the largest index which contains 7!</p></blockquote>
<p>I would like to thank <span style="text-decoration:bold;color:#ff0000;"><strong><a href="http://www.topcoder.com/tc?module=MemberProfile&amp;cr=7390467&amp;tab=alg">lovro</a></strong></span> for the tutorial on binary search that has helped me out a lot <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codeoverflow.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codeoverflow.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codeoverflow.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codeoverflow.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codeoverflow.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codeoverflow.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codeoverflow.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codeoverflow.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codeoverflow.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codeoverflow.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codeoverflow.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codeoverflow.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codeoverflow.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codeoverflow.wordpress.com/18/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeoverflow.wordpress.com&amp;blog=17915630&amp;post=18&amp;subd=codeoverflow&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codeoverflow.wordpress.com/2010/11/23/binary-search-nightmares/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/bb17aa8ea5a28152343e1c1b07a2467c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ashagrwal</media:title>
		</media:content>
	</item>
		<item>
		<title>HDCP: The LEAK and the NOTES !</title>
		<link>http://codeoverflow.wordpress.com/2010/09/23/hdcp-the-leak-and-the-notes/</link>
		<comments>http://codeoverflow.wordpress.com/2010/09/23/hdcp-the-leak-and-the-notes/#comments</comments>
		<pubDate>Thu, 23 Sep 2010 12:30:00 +0000</pubDate>
		<dc:creator>SwitchCase</dc:creator>
				<category><![CDATA[Security]]></category>
		<category><![CDATA[cryptography]]></category>
		<category><![CDATA[DVI]]></category>
		<category><![CDATA[HDCP]]></category>
		<category><![CDATA[HDMI]]></category>

		<guid isPermaLink="false">http://codeoverflow.wordpress.com/2010/09/23/hdcp-the-leak-and-the-notes</guid>
		<description><![CDATA[Hi, This is the first official (read meaningful) post on this blog. And as the title suggests, it is about the recent HDCP key leak. What is HDCP: High-Bandwidth Digital Content Protection. It is used as an encryption to protect digital formats( video/audio) so that the data being transferred over the wire (usually Digital Visual <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeoverflow.wordpress.com&amp;blog=17915630&amp;post=16&amp;subd=codeoverflow&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Hi,</p>
<p>This is the first official (read meaningful) post on this blog. And as the title suggests, it is about the recent HDCP key leak.</p>
<p><b><u>What is HDCP</u></b>: High-Bandwidth Digital Content Protection. It is used as an encryption to protect digital formats( video/audio) so that the data being transferred over the wire (usually Digital Visual Interface -DVI , High Definition Multimedia Interface &#8211; HDMI) is secure and not copied off the wire.</p>
<p><b><u>How Does it work</u></b> : It uses a very common trick : Identification. But to make sure that unscrupluous people don&#8217;t tamper, there is a protocol to identify. When a vendor makes a HDCP compliant device, he procures a license from Digital Content Protection LLC. The license contains two vectors u and v. u is the private key and v is a public key. v is also called the Key Selection vector(KSV) and as per HDCP specs, it must have a hamming weight of 20. Both u and v are 56-bits.</p>
<p><span class="Apple-tab-span" style="white-space:pre;"> </span>When two devices(transmitter and receiver) wish to communicate they exchange their public keys (v) or KSVs. Then they each compute the dot product of their private key (u) with the other device&#8217;s KSV. Then the transmitter sends a nonce(number used once) to the receiver. The receiver performs a non-invertible function h on the dot product it generated and the nonce. It replies back with a 16-bit number and the transmitter does the same. When these two numbers match, it assumes that the other device is HDCP compliant and begins the transfer of digital data (encrypted).<br /><span class="Apple-tab-span" style="white-space:pre;"> </span><br /><span class="Apple-tab-span" style="white-space:pre;"> </span>Now, for all this to work, both the dot products calculated must be the same. For that to happen, the private key must be made in a special way. They use a 40 by 40 matrix key generator which generates the private vector. This can be called as a master key. If anyone has this master key, he can open any lock he likes!</p>
<p><b><u>The Problem</u></b>: All this sounds really good. The numbers are 56-bits and to that fact with a hamming weight of 20, it is near impossible to generate a key randomly by any processor in this era. BUT (In Computers, there is always a big BUT, isn&#8217;t it ?), what if we had 40 valid keys(private keys)- then would it be possible. YES. This fact has been known for a long time and there is a paper that shows this !</p>
<p>In reality what happens is that there are two private keys :; source and sink. Depending on whether the device is a transmitter or reciever it uses the source or sink keys as the private key.</p>
<p><u><b>LETS DO IT !!</b></u> : Well, I would love to. But I don&#8217;t have 40 keys (darn!). However, we could use an example and see if this is infact possible !<br />Lets consider 4 devices &#8211; A, B, C, D. <b>The private keys (source) are</b><br /><TABLE width="30%" border="0" cellspacing="4" cellpadding="5"><br />
<tr>
<td>A</td>
<td>9</td>
<td>13</td>
<td>0</td>
<td>4</td>
</tr>
<tr>
<td>B</td>
<td>12</td>
<td>1</td>
<td>4</td>
<td>8</td>
</tr>
<tr>
<td>C</td>
<td>6</td>
<td>5</td>
<td>9</td>
<td>15</td>
</tr>
<tr>
<td>D</td>
<td>15</td>
<td>12</td>
<td>15</td>
<td>5</td>
</tr>
<p></TABLE><br /> <br /> <b>and for sinks :</b><br /><TABLE width="30%" border="0" cellspacing="4" cellpadding="5"><br />
<tr>
<td>A</td>
<td>4</td>
<td>11</td>
<td>5</td>
<td>10</td>
</tr>
<tr>
<td>B</td>
<td>5</td>
<td>13</td>
<td>8</td>
<td>6</td>
</tr>
<tr>
<td>C</td>
<td>8</td>
<td>0</td>
<td>12</td>
<td>12</td>
</tr>
<tr>
<td>D</td>
<td>6</td>
<td>13</td>
<td>7</td>
<td>14</td>
</tr>
<p></TABLE><br /> The corresponding KSV for the four devices  {1010, 0110, 0011,1001 } (in binary).</p>
<p>Now if A and B wish to communicate and A is source and B is sink. They would first exchange the KSV. Then it applies the other device&#8217;s KSV on its private key to get a number. For simplicity, lets assume they just check whether they are equal directly. So A would get = 13+0=13 (adding 2nd and 3rd elements) and B would get = 5+8=13 (adding 1st and 3rd). Since they are equal, they proceed !!</p>
<p>But now, we have a fourth Device E. We know the public key (since its public and all!) but the private key is unknown. We will assume that E is a sink device and its key is (a,b,c,d).<br />Now, if we pair every known device with E, we will be able to get simultaneous equations (four in number) and anyone who knows linear algebra knows that 4 equations and 4 variables = solvable!!</p>
<p>Thus to replicate a 40 element vector, we would only need 40 valid keys!</p>
<p>Thus we can replicate or rather impersonate any device as HDCP compliant without even being!</p>
<p>I hope you enjoyed reading it. Most of the information posted here has been collected from various blogs around the net, and I thank them all for explaining it in great detail.</p>
<p>I am also posting the links :<br /><a href="http://citeseer.ist.psu.edu/cache/papers/cs/25911/http:zSzzSzwww.cs.berkeley.eduzSz~dawzSzpaperszSzhdcp-drm01.pdf/a-cryptanalysis-of-the.pdf">Crosby Paper</a> <br /><a href="http://pastebin.com/kqD56TmU">THE LEAKED KEY !</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codeoverflow.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codeoverflow.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codeoverflow.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codeoverflow.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codeoverflow.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codeoverflow.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codeoverflow.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codeoverflow.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codeoverflow.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codeoverflow.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codeoverflow.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codeoverflow.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codeoverflow.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codeoverflow.wordpress.com/16/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeoverflow.wordpress.com&amp;blog=17915630&amp;post=16&amp;subd=codeoverflow&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codeoverflow.wordpress.com/2010/09/23/hdcp-the-leak-and-the-notes/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/bb17aa8ea5a28152343e1c1b07a2467c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ashagrwal</media:title>
		</media:content>
	</item>
		<item>
		<title>Hi Everyone.</title>
		<link>http://codeoverflow.wordpress.com/2010/09/20/hi-everyone/</link>
		<comments>http://codeoverflow.wordpress.com/2010/09/20/hi-everyone/#comments</comments>
		<pubDate>Mon, 20 Sep 2010 10:22:00 +0000</pubDate>
		<dc:creator>SwitchCase</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://codeoverflow.wordpress.com/2010/09/20/hi-everyone</guid>
		<description><![CDATA[PS: I know no one is there but still its worth a shot.. ain&#8217;t it ! Anyhow, to the nomad who accidentally ended on this page. I am sorry for you. But since you are here anyway, I&#8217;ll tell you what this one is about. Just another GEEK ranting about the things he likes !<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeoverflow.wordpress.com&amp;blog=17915630&amp;post=17&amp;subd=codeoverflow&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>PS: I know no one is there but still its worth a shot.. ain&#8217;t it !</p>
<p>Anyhow, to the nomad who accidentally ended on this page. I am sorry for you. But since you are here anyway, I&#8217;ll tell you what this one is about. Just another GEEK ranting about the things he likes !</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codeoverflow.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codeoverflow.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codeoverflow.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codeoverflow.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codeoverflow.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codeoverflow.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codeoverflow.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codeoverflow.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codeoverflow.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codeoverflow.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codeoverflow.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codeoverflow.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codeoverflow.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codeoverflow.wordpress.com/17/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeoverflow.wordpress.com&amp;blog=17915630&amp;post=17&amp;subd=codeoverflow&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codeoverflow.wordpress.com/2010/09/20/hi-everyone/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/bb17aa8ea5a28152343e1c1b07a2467c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ashagrwal</media:title>
		</media:content>
	</item>
	</channel>
</rss>
