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

<channel>
	<title>0plus1 Blog &#187; Code Snippets</title>
	<atom:link href="http://0plus1.com/blog/tag/code-snippets/feed/" rel="self" type="application/rss+xml" />
	<link>http://0plus1.com/blog</link>
	<description>Code snippets and programming resources</description>
	<lastBuildDate>Sat, 15 Jan 2011 15:09:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.4</generator>
		<item>
		<title>Facebook Hacker Cup 2011 Qualification &#8211; Double Squares</title>
		<link>http://0plus1.com/blog/2011/01/facebook-hacker-cup-2011-round-1-double-squares/</link>
		<comments>http://0plus1.com/blog/2011/01/facebook-hacker-cup-2011-round-1-double-squares/#comments</comments>
		<pubDate>Sat, 08 Jan 2011 23:10:44 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[facebook]]></category>
		<category><![CDATA[hacker challenge]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://0plus1.com/blog/?p=50</guid>
		<description><![CDATA[Most of the programmers now about the Hacker Challenge from Facebook. I will now explain my take on it using php. The reason I&#8217;m doing this is because this contest is an epic fail (read here the reasons why) full of bug, with really confused rules badly explained (I&#8217;m looking at you 6 minutes time [...]]]></description>
			<content:encoded><![CDATA[<p>Most of the programmers now about the <a href="http://www.facebook.com/event.php?eid=148059031890072">Hacker Challenge</a> from Facebook. I will now explain my take on it using php.<br />
The reason I&#8217;m doing this is because this contest is an epic fail (<a href="http://www.quora.com/Andrew-Brown-2/Facebook-Hacker-Cup-Resounding-Failure">read here the reasons why</a>) full of bug, with really confused rules badly explained (I&#8217;m looking at you 6 minutes time limit with no warning and the code/no-code in the reply question). Anyway it&#8217;s still an interesting programming puzzle..</p>
<p>Let us start with the text of the problem:</p>
<blockquote><p>Double Squares<br />
A double-square number is an integer X which can be expressed as the sum of two perfect squares. For example, 10 is a double-square because 10 = 3<sup>2</sup> + 1<sup>2</sup>. Your task in this problem is, given X, determine the number of ways in which it can be written as the sum of two squares. For example, 10 can only be written as 3<sup>2</sup> + 1<sup>2</sup> (we don&#8217;t count 1<sup>2</sup> + 3<sup>2</sup> as being different). On the other hand, 25 can be written as 5<sup>2</sup> + 0<sup>2</sup> or as 4<sup>2</sup> + 3<sup>2</sup>.</p>
<p>Input<br />
You should first read an integer N, the number of test cases. The next N lines will contain N values of X.<br />
Constraints<br />
0  &lt;  X  &lt;  2147483647<br />
1  &lt; N  &lt; 100<br />
Output<br />
For each value of X, you should output the number of ways to write X as the sum of two squares.</p></blockquote>
<p>Facebook right at the top of the page gives you an hint: <strong>Too hard for brute force, switching to dp</strong><br />
This is because the problems that have been given are fairly easy to code using brute force, but hard to do the smart way, since we are using php here the smart way is the only way to go (you&#8217;ll see the reason in a while).</p>
<p>Let&#8217;s start.</p>
<p>First thing is to read the input, easy one.. since I like multidimensional arrays I did it like this:</p>
<pre class="brush: php; title: ;">
function fromTxtToArray($filename){
	$fh = fopen($filename, &quot;rb&quot;);
	$data = fread($fh, filesize($filename));
	fclose($fh);

	$array = explode(&quot;\n&quot;,$data);
	$rows = $array[0];
	unset($array[0]);

	return array('rows' =&gt; $rows, 'data' =&gt; $array);
}
</pre>
<p>Then we have the main cycle (I discarded completely the rows because I like foreach better than for):</p>
<pre class="brush: php; title: ;">
$data = fromTxtToArray('input.txt');
foreach ($data['data'] as $k =&gt; $v){
    //?????
}
</pre>
<p>Now that the main logic is out of the way let&#8217;s work the problem, starting with the:</p>
<p><strong>bruteforcing method</strong></p>
<pre class="brush: php; title: ;">

function scompose($number){
	$array = array();

	if ($number % 2 == 0) {
		$stop = $number/2;
	} else {
		$stop = round($number/2, 0, PHP_ROUND_HALF_DOWN);
	}

	for($i=0;$i&lt;=$number;$i++){

		if($i&gt;$stop){
			break;
		}
		$num1 = $number-$i;
		$num2 = $i;

		if(isPerfect($num1)&amp;&amp;isPerfect($num2)){
			$array[] = array('num1'=&gt;$num1,'num2'=&gt;$num2);
		}
	}

	return $array;
}

$data = fromTxtToArray('input.txt');

set_time_limit(0);

foreach ($data['data'] as $k =&gt; $v){
     echo count(scompose($v)).&quot;\n&quot;;
}
</pre>
<p>Basically what this does is to cycle the number in order to get all of his possible couple of addends, it does this simply by subtracting $i from the number and taking $i as the other addend. Now this will create a real issue because doing so will give you repeated couples (eg: take five you&#8217;ll get 0,5;1,4;2,3;3,2;4,1;5,0) this is wrong since the problem text clearly states that there shouldn&#8217;t be repetition. To avoid this we have to divide the number by two, rounding him down in case it&#8217;s odd, using this value we can break the cycle when we get to that point. After that we check if both of the addends of the numbers are perfect squares if so we put them in an array, when the cycle stops we count the array and we are done. The missing functions are these:</p>
<pre class="brush: php; title: ;">
//Avoids problem with the buggy is_int native php function
function betterIs_int($int){

	if(is_numeric($int) === true){
		if((int)$int == $int){
			return true;
		} else {
			return false;
		}
	}else{
		return false;
	}
}
//Check if the square root of a number is an integer (perfect square)
function isPerfect($int){
	if(betterIs_int(sqrt($int))){
		return true;
	} else {
		return false;
	}
}
</pre>
<p>I actually let this thing run for fun with the input.txt file and I stopped it after 14 minutes! It works with the examples though, just use this:</p>
<pre class="brush: php; title: ;">
$data['data']= array('10','25','3','0','1');
</pre>
<p>Let&#8217;s move to the:</p>
<p><strong>Dynamic programming</strong></p>
<p>If you are not acquainted with this methodology please read <a href="http://en.wikipedia.org/wiki/Dynamic_programming">here</a> and <a href="http://stackoverflow.com/questions/4278188/good-examples-articles-books-for-understanding-dynamic-programming">here</a>.</p>
<p>The problem we had with the brute force was that the for cycle was very very loooong, we have to find a better way to approach this! See we are checking every couple to see if they&#8217;re perfect square  what about a method where we can rule out directly if there are? First we have to find the highest possible square root of the number, since we cannot exceed this number we have less cases to test. Then we cycle $i from 0 to the maxsquare and we check if the square root of the difference between the number and the square of $i is an integer, if it is we have a winning couple! But wait we still have a problem, the couples are once again repeated! We have to divide them by 2.</p>
<pre class="brush: php; title: ;">
function firstDraft($number){

    if($number==0||$number==1){
	        return 1;
	}

	$result=0;

	$maxsquare = floor(sqrt($number));

	for ($i=0; $i&lt;$maxsquare;$i++) {

		$difference = sqrt($number-($i*$i));

		if (betterIs_int($difference)) {
			$result++;
		}
	}
	return ceil($result/2);
}
</pre>
<p>Wait! Divide them by two? Why? We could just calculate the half square root of the number and trim down the cases to test! And so..</p>
<pre class="brush: php; title: ;">
function dp($number){

    if($number==0||$number==1){
	        return 1;
	}

	$result=0;

	$halfmaxsquare = ceil(sqrt($number/2));

	for ($i=0; $i&lt;$halfmaxsquare;$i++) {

		$difference = sqrt($number-($i*$i));

		if (betterIs_int($difference)) {
			$result++;
		}
	}
	return $result;
}

$data = fromTxtToArray('input.txt');

foreach ($data['data'] as $k =&gt; $v){
	echo dp($v).&quot;\n&quot;;
}
</pre>
<p>No need to set time limit here <img src='http://0plus1.com/blog/wp-includes/images/smilies/icon_razz.gif' alt=':-P' class='wp-smiley' /><br />
enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://0plus1.com/blog/2011/01/facebook-hacker-cup-2011-round-1-double-squares/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>print_r output beautifier</title>
		<link>http://0plus1.com/blog/2009/05/print_r-output-beautifier/</link>
		<comments>http://0plus1.com/blog/2009/05/print_r-output-beautifier/#comments</comments>
		<pubDate>Wed, 13 May 2009 15:42:04 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[print_r]]></category>

		<guid isPermaLink="false">http://0plus1.com/blog/?p=9</guid>
		<description><![CDATA[Today I wrote a script that needed to manipulate several multidimensional arrays, some of them pretty deep. The standard php function print_r is an hellish mess, browsing through the marvellous php.net documentation I&#8217;ve found several examples to beautify the output of print_r (just to give credit: &#8220;Bob&#8221; and &#8220;Everett&#8221; were my inspiration) since no one [...]]]></description>
			<content:encoded><![CDATA[<p>Today I wrote a script that needed to manipulate several multidimensional arrays, some of them pretty deep.</p>
<p>The standard php function print_r is an hellish mess, browsing through the marvellous php.net documentation I&#8217;ve found several examples to beautify the output of print_r (just to give credit: &#8220;Bob&#8221; and &#8220;Everett&#8221; were my inspiration) since no one actually did it the way I wanted I made a custom one myself:</p>
<pre class="brush: php; title: ;">
function print_rr($array){
    foreach($array as $key=&gt;$value){
       if(is_array($value)){
          $id = md5(rand());
          echo '[&lt;a href=&quot;#&quot; onclick=&quot;return expandParent(\''.$id.'\')&quot;&gt;'.$key.'&lt;/a&gt;]&lt;br /&gt;';
          echo '&lt;div id=&quot;'.$id.'&quot; style=&quot;display:none;margin:10px;border-left:1px solid; padding-left:5px;&quot;&gt;';
          print_rr($value, $count);
          echo '&lt;/div&gt;';
       } else {
       echo &quot;&lt;b&gt;$key&lt;/b&gt;: &quot;.$value.&quot;&lt;br /&gt;&quot;;
       }
    }
echo '&lt;script language=&quot;Javascript&quot;&gt;
function expandParent(id){toggle=&quot;block&quot;;if(document.getElementById(id).style.display==&quot;block&quot;){toggle=&quot;none&quot;}document.getElementById(id).style.display=toggle};
&lt;/script&gt;';
}
</pre>
<p>Feel free to use it anyway you like it.</p>
]]></content:encoded>
			<wfw:commentRss>http://0plus1.com/blog/2009/05/print_r-output-beautifier/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

