<?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>GilgaLab</title>
	<atom:link href="http://www.gilgalab.com.br/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.gilgalab.com.br</link>
	<description></description>
	<lastBuildDate>Mon, 07 Nov 2011 07:38:14 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Problems with the blog</title>
		<link>http://www.gilgalab.com.br/2011/11/07/problems-with-the-blog/</link>
		<comments>http://www.gilgalab.com.br/2011/11/07/problems-with-the-blog/#comments</comments>
		<pubDate>Mon, 07 Nov 2011 07:38:14 +0000</pubDate>
		<dc:creator>Henrique</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Blog status]]></category>

		<guid isPermaLink="false">http://www.gilgalab.com.br/?p=262</guid>
		<description><![CDATA[Good morning few readers :) It came to my attention the blog was having some trouble with all the links to posts redirecting to an error page. There is a problem with mod_rewrite in the server it seems (like it is not installed, because I switched to a different server and didn't notice such 'detail'). [...]]]></description>
			<content:encoded><![CDATA[<p>Good morning few readers :)</p>
<p>It came to my attention the blog was having some trouble with all the links to posts redirecting to an error page. There is a problem with mod_rewrite in the server it seems (like it is not installed, because I switched to a different server and didn't notice such 'detail').<br />
I am sorry for any problems this might have caused, I will try to solve this today. Meanwhile I have switched the URL style back to '?p=number_here', so everyon can navigate.</p>
<p>Again, sorry about this :$<br />
If you find any other problems, please leave a comment so I can look into it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.gilgalab.com.br/2011/11/07/problems-with-the-blog/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Project Euler &#8211; Problem 28</title>
		<link>http://www.gilgalab.com.br/2011/07/08/project-euler-problem-28/</link>
		<comments>http://www.gilgalab.com.br/2011/07/08/project-euler-problem-28/#comments</comments>
		<pubDate>Fri, 08 Jul 2011 07:16:10 +0000</pubDate>
		<dc:creator>Henrique</dc:creator>
				<category><![CDATA[C]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Project Euler]]></category>

		<guid isPermaLink="false">http://www.gilgalab.com.br/?p=255</guid>
		<description><![CDATA[Alright! I have been away for a while as there are too many things happening right now and I have been pretty busy. Well, this time I will resolve Problem 28 from Projet Euler. For this, I will use mostly a manual method for deducing the formulas and then a small C program to finish [...]]]></description>
			<content:encoded><![CDATA[<p>Alright!<br />
I have been away for a while as there are too many things happening right now and I have been pretty busy.<br />
Well, this time I will resolve Problem 28 from <a href="http://www.projecteuler.net/" target="_blank">Projet Euler</a>. For this, I will use mostly a manual method for deducing the formulas and then a small C program to finish the sum for us :)<br />
The problem states:</p>
<blockquote>
<p>Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:</p>
<p style='text-align:center;font-family:courier new;'><span style='color:#ff0000;font-family:courier new;'><b>21</b></span> 22 23 24 <span style='color:#ff0000;font-family:courier new;'><b>25</b></span><br />
20 &nbsp;<span style='color:#ff0000;font-family:courier new;'><b>7</b></span> &nbsp;8 &nbsp;<span style='color:#ff0000;font-family:courier new;'><b>9</b></span> 10<br />
19 &nbsp;6 &nbsp;<span style='color:#ff0000;font-family:courier new;'><b>1</b></span> &nbsp;2 11<br />
18 &nbsp;<span style='color:#ff0000;font-family:courier new;'><b>5</b></span> &nbsp;4 &nbsp;<span style='color:#ff0000;font-family:courier new;'><b>3</b></span> 12<br />
<span style='color:#ff0000;font-family:courier new;'><b>17</b></span> 16 15 14 <span style='color:#ff0000;font-family:courier new;'><b>13</b></span></p>
<p>It can be verified that the sum of the numbers on the diagonals is 101.</p>
<p>What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?</p>
</blockquote>
<p>According to the problem for this spiral the sum is 101 because: 1 + 3 + 5 + 7 + 9 + 13 + 17 + 21 + 25 = 101<br />
Good! So in order to resolve this problem all we have to do is figure out what are the rules that guide the diagonal numbers.</p>
<p>I have divided this spiral in 4 diagonals:</p>
<ul>
<li style='color:#F27900'>Center to right upper corner</li>
<li style='color:#ff0000'>Center to right lower corner</li>
<li style='color:#8E0079'>Center to left lower corner</li>
<li style='color:#006899'>Center to left upper corner</li>
</ul>
<p>If we expand this spiral a a little bit more, we will have:</p>
<p style='text-align:center;font-family:courier new;'>
<span style='color:#006899;font-family:courier new;'><b>73</b></span> 74 75 76 77 78 79 80 <span style='color:#F27900;font-family:courier new;'><b>81</b></span><br />
72 <span style='color:#006899;font-family:courier new;'><b>43</b></span> 44 45 46 47 48 <span style='color:#F27900;font-family:courier new;'><b>49</b></span> 50<br />
71 42 <span style='color:#006899;font-family:courier new;'><b>21</b></span> 22 23 24 <span style='color:#F27900;font-family:courier new;'><b>25</b></span> 26 51<br />
70 41 20 <span style='color:#006899;font-family:courier new;'><b>07</b></span> 08 <span style='color:#F27900;font-family:courier new;'><b>09</b></span> 10 27 52<br />
69 40 19 06 <span style='color:#000000;font-family:courier new;'><b>01</b></span> 02 11 28 53<br />
68 39 18 <span style='color:#8E0079;font-family:courier new;'><b>05</b></span> 04 <span style='color:#ff0000;font-family:courier new;'><b>03</b></span> 12 29 54<br />
67 38 <span style='color:#8E0079;font-family:courier new;'><b>17</b></span> 16 15 14 <span style='color:#ff0000;font-family:courier new;'><b>13</b></span> 30 55<br />
66 <span style='color:#8E0079;font-family:courier new;'><b>37</b></span> 36 35 34 33 32 <span style='color:#ff0000;font-family:courier new;'><b>31</b></span> 56<br />
<span style='color:#8E0079;font-family:courier new;'><b>65</b></span> 64 63 62 61 60 59 58 <span style='color:#ff0000;font-family:courier new;'><b>57</b></span>
</p>
<p>Based on this we can deduce the formulas that generates each diagonal.</p>
<p><b>1. </b><b style='color:#F27900'>Center to right upper corner (1, 9, 25, 49, 81, ...)</b></p>
<p>    For this one, we can see that for each level that expands, we have a squared number. So if we put a little bit of thinking on it, we can come up with the following formula:</p>
<p><img src='http://s.wordpress.com/latex.php?latex=%20%20%20%20%20%20f%28n%29%20%3D%20%282%2An%2B1%29%5E2%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='      f(n) = (2*n+1)^2  ' title='      f(n) = (2*n+1)^2  ' class='latex' /><br />
<br />
    Where n is the number of the line counting from the center up (The first line being 0)<br />
    You can try it!</p>
<p><img src='http://s.wordpress.com/latex.php?latex=%20%20%20%20%20%20f%280%29%20%3D%20%282%2A0%2B1%29%5E2%20%3D%20%281%29%5E2%20%3D%201%5C%5C%20%20%20%20%20%20f%281%29%20%3D%20%282%2A1%2B1%29%5E2%20%3D%20%283%29%5E2%20%3D%209%5C%5C%20%20%20%20%20%20f%282%29%20%3D%20%282%2A2%2B1%29%5E2%20%3D%20%285%29%5E2%20%3D%2025%5C%5C%20%20%20%20%20%20f%283%29%20%3D%20%282%2A3%2B1%29%5E2%20%3D%20%287%29%5E2%20%3D%2049%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='      f(0) = (2*0+1)^2 = (1)^2 = 1\\      f(1) = (2*1+1)^2 = (3)^2 = 9\\      f(2) = (2*2+1)^2 = (5)^2 = 25\\      f(3) = (2*3+1)^2 = (7)^2 = 49  ' title='      f(0) = (2*0+1)^2 = (1)^2 = 1\\      f(1) = (2*1+1)^2 = (3)^2 = 9\\      f(2) = (2*2+1)^2 = (5)^2 = 25\\      f(3) = (2*3+1)^2 = (7)^2 = 49  ' class='latex' /><br />
<br />
<b>2. </b><b style='color:#ff0000'>Center to right lower corner (1, 3, 13, 31, 57, ...)</b></p>
<p>    Comparing the results from the center to right upper corner results, we notice that the value here is the same as that diagonal minus 6*n. So the formula goes:</p>
<p><img src='http://s.wordpress.com/latex.php?latex=%20%20%20%20%20%20f%28n%29%20%3D%20%28%282%2An%2B1%29%5E2%29%20-%206%2An%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='      f(n) = ((2*n+1)^2) - 6*n  ' title='      f(n) = ((2*n+1)^2) - 6*n  ' class='latex' /><br />
<br /> <br />
    Where n is the number of the line counting from the center down (The first line being 0)<br />
    You can try it!</p>
<p><img src='http://s.wordpress.com/latex.php?latex=%20%20%20%20%20%20f%280%29%20%3D%20%28%282%2A0%2B1%29%5E2%29%20-%206%2A0%20%3D%20%281%29%5E2%20-%200%20%20%3D%201%5C%5C%20%20%20%20%20%20f%281%29%20%3D%20%28%282%2A1%2B1%29%5E2%29%20-%206%2A1%20%3D%20%283%29%5E2%20-%206%20%20%3D%203%5C%5C%20%20%20%20%20%20f%282%29%20%3D%20%28%282%2A2%2B1%29%5E2%29%20-%206%2A2%20%3D%20%285%29%5E2%20-%2012%20%3D%2013%5C%5C%20%20%20%20%20%20f%283%29%20%3D%20%28%282%2A3%2B1%29%5E2%29%20-%206%2A3%20%3D%20%287%29%5E2%20-%2018%20%3D%2031%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='      f(0) = ((2*0+1)^2) - 6*0 = (1)^2 - 0  = 1\\      f(1) = ((2*1+1)^2) - 6*1 = (3)^2 - 6  = 3\\      f(2) = ((2*2+1)^2) - 6*2 = (5)^2 - 12 = 13\\      f(3) = ((2*3+1)^2) - 6*3 = (7)^2 - 18 = 31  ' title='      f(0) = ((2*0+1)^2) - 6*0 = (1)^2 - 0  = 1\\      f(1) = ((2*1+1)^2) - 6*1 = (3)^2 - 6  = 3\\      f(2) = ((2*2+1)^2) - 6*2 = (5)^2 - 12 = 13\\      f(3) = ((2*3+1)^2) - 6*3 = (7)^2 - 18 = 31  ' class='latex' /><br />
<br />
<b>3. </b><b style='color:#8E0079'>Center to left lower corner (1, 5, 17, 37, 65, ...)</b></p>
<p>    Comparing the results from the center to right upper corner results, we notice that the value here is the same as that diagonal minus 4*n. So the formula goes:</p>
<p><img src='http://s.wordpress.com/latex.php?latex=%20%20%20%20%20%20f%28n%29%20%3D%20%282%2An%2B1%29%5E2-4n%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='      f(n) = (2*n+1)^2-4n  ' title='      f(n) = (2*n+1)^2-4n  ' class='latex' /><br />
<br />
    Where n is the number of the line counting from the center down (The first line being 0)<br />
    You can also try this one!</p>
<p><img src='http://s.wordpress.com/latex.php?latex=%20%20%20%20%20%20f%280%29%20%3D%20%282%2An%2B1%29%5E2-4n%20%3D%20%281%29%5E2%20-%200%20%3D%201%5C%5C%20%20%20%20%20%20f%281%29%20%3D%20%282%2An%2B1%29%5E2-4n%20%3D%20%283%29%5E2%20-%204%20%3D%205%5C%5C%20%20%20%20%20%20f%282%29%20%3D%20%282%2An%2B1%29%5E2-4n%20%3D%20%285%29%5E2%20-%208%20%3D%2017%5C%5C%20%20%20%20%20%20f%283%29%20%3D%20%282%2An%2B1%29%5E2-4n%20%3D%20%287%29%5E2%20-%2012%20%3D%2037%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='      f(0) = (2*n+1)^2-4n = (1)^2 - 0 = 1\\      f(1) = (2*n+1)^2-4n = (3)^2 - 4 = 5\\      f(2) = (2*n+1)^2-4n = (5)^2 - 8 = 17\\      f(3) = (2*n+1)^2-4n = (7)^2 - 12 = 37  ' title='      f(0) = (2*n+1)^2-4n = (1)^2 - 0 = 1\\      f(1) = (2*n+1)^2-4n = (3)^2 - 4 = 5\\      f(2) = (2*n+1)^2-4n = (5)^2 - 8 = 17\\      f(3) = (2*n+1)^2-4n = (7)^2 - 12 = 37  ' class='latex' /><br />
<br /> <br />
<b>4. </b><b style='color:#006899'>Center to left upper corner (1, 7, 21, 43, 73, ...)</b></p>
<p>    Comparing the results from the center to right upper corner results, we notice that the value here is the same as that diagonal minus 2*n. So the formula goes:</p>
<p><img src='http://s.wordpress.com/latex.php?latex=%20%20%20%20%20%20f%28n%29%20%3D%20%282%2An%2B1%29%5E2-2n%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='      f(n) = (2*n+1)^2-2n  ' title='      f(n) = (2*n+1)^2-2n  ' class='latex' /><br />
<br />
    Where n is the number of the line counting from the center up (The first line being 0)<br />
    And once again you can try this one!</p>
<p><img src='http://s.wordpress.com/latex.php?latex=%20%20%20%20%20%20f%280%29%20%3D%20%282%2An%2B1%29%5E2-2n%20%3D%20%281%29%5E2%20-%200%20%3D%201%5C%5C%20%20%20%20%20%20f%281%29%20%3D%20%282%2An%2B1%29%5E2-2n%20%3D%20%283%29%5E2%20-%202%20%3D%207%5C%5C%20%20%20%20%20%20f%282%29%20%3D%20%282%2An%2B1%29%5E2-2n%20%3D%20%285%29%5E2%20-%204%20%3D%2021%5C%5C%20%20%20%20%20%20f%283%29%20%3D%20%282%2An%2B1%29%5E2-2n%20%3D%20%287%29%5E2%20-%206%20%3D%2043%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='      f(0) = (2*n+1)^2-2n = (1)^2 - 0 = 1\\      f(1) = (2*n+1)^2-2n = (3)^2 - 2 = 7\\      f(2) = (2*n+1)^2-2n = (5)^2 - 4 = 21\\      f(3) = (2*n+1)^2-2n = (7)^2 - 6 = 43  ' title='      f(0) = (2*n+1)^2-2n = (1)^2 - 0 = 1\\      f(1) = (2*n+1)^2-2n = (3)^2 - 2 = 7\\      f(2) = (2*n+1)^2-2n = (5)^2 - 4 = 21\\      f(3) = (2*n+1)^2-2n = (7)^2 - 6 = 43  ' class='latex' /><br />
<br />
Now we need to figure out from what value to what value our <b>'n'</b> should range. We know the following about our grid:</p>
<ul>
<li>When the grid is 3x3, we have 9  (3^2) at the right top corner
<li>When the grid is 5x5, we have 25 (5^2) at the right top corner
<li>When the grid is 7x7, we have 49 (7^2) at the right top corner
<li>When the grid is 9x9, we have 81 (9^2) at the right top corner
<li>When the grid is 1001x1001, we have 1002001 (1001^2) at the right top corner
</ul>
<p>Based on this we can conclude that we will have 500 lines up, 500 lines down and one line in the center, each line with 1001 rows.<br />
Our sums should look like this then:</p>
<p><img src='http://s.wordpress.com/latex.php?latex=%20%20%20%20%20%20%5Csum_%7Bn%20%3D%200%7D%5E%7B500%7D%20%282%2An%2B1%29%5E2%20%5C%5C%20%20%20%20%20%20%5C%5C%20%20%20%20%20%20%5Csum_%7Bn%20%3D%200%7D%5E%7B500%7D%20%282%2An%2B1%29%5E2%20-%206%2An%20%5C%5C%20%20%20%20%20%20%5C%5C%20%20%20%20%20%20%5Csum_%7Bn%20%3D%200%7D%5E%7B500%7D%20%282%2An%2B1%29%5E2%20-%204%2An%20%5C%5C%20%20%20%20%20%20%5C%5C%20%20%20%20%20%20%5Csum_%7Bn%20%3D%200%7D%5E%7B500%7D%20%282%2An%2B1%29%5E2%20-%202%2An%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='      \sum_{n = 0}^{500} (2*n+1)^2 \\      \\      \sum_{n = 0}^{500} (2*n+1)^2 - 6*n \\      \\      \sum_{n = 0}^{500} (2*n+1)^2 - 4*n \\      \\      \sum_{n = 0}^{500} (2*n+1)^2 - 2*n  ' title='      \sum_{n = 0}^{500} (2*n+1)^2 \\      \\      \sum_{n = 0}^{500} (2*n+1)^2 - 6*n \\      \\      \sum_{n = 0}^{500} (2*n+1)^2 - 4*n \\      \\      \sum_{n = 0}^{500} (2*n+1)^2 - 2*n  ' class='latex' /><br />
<br />
We calculate them all and sum them all together. After this is done, we subtract 3 from the sum because in them all we have added the element in the middle of the grid (1), so we have summed the number 1 four times, and the exercise asks us to sum all the numbers in the diagonals, meaning we should add each one of them only once.<br />
We can than use <a href="http://www.wolframalpha.com" target="_blank">WolframAlpha</a> to calculate this sum, or just write a simple C code for it:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;stdio.h&gt;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">int</span> n<span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">long</span> <span style="color: #993333;">long</span> sum <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>n <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> n <span style="color: #339933;">&lt;=</span> <span style="color: #0000dd;">500</span><span style="color: #339933;">;</span> n<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        sum <span style="color: #339933;">+=</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">2</span><span style="color: #339933;">*</span>n<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">2</span><span style="color: #339933;">*</span>n<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>       <span style="color: #666666; font-style: italic;">// Same as (2*n+1)^2</span>
        sum <span style="color: #339933;">+=</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">2</span><span style="color: #339933;">*</span>n<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">2</span><span style="color: #339933;">*</span>n<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> <span style="color: #0000dd;">6</span><span style="color: #339933;">*</span>n<span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// Same as (2*n+1)^2 - 6*n</span>
        sum <span style="color: #339933;">+=</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">2</span><span style="color: #339933;">*</span>n<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">2</span><span style="color: #339933;">*</span>n<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> <span style="color: #0000dd;">4</span><span style="color: #339933;">*</span>n<span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// Same as (2*n+1)^2 - 4*n</span>
        sum <span style="color: #339933;">+=</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">2</span><span style="color: #339933;">*</span>n<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">2</span><span style="color: #339933;">*</span>n<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> <span style="color: #0000dd;">2</span><span style="color: #339933;">*</span>n<span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// Same as (2*n+1)^2 - 2*n</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Result is: %llu&quot;</span><span style="color: #339933;">,</span> sum<span style="color: #339933;">-</span><span style="color: #0000dd;">3</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>I will leave it up to the user to execute the above code to get the result, or to calculate the formulas using some tool.<br />
Hope you enjoyed! :)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.gilgalab.com.br/2011/07/08/project-euler-problem-28/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Python C API &#8211; Second Step</title>
		<link>http://www.gilgalab.com.br/2011/05/03/python-c-api-second-step/</link>
		<comments>http://www.gilgalab.com.br/2011/05/03/python-c-api-second-step/#comments</comments>
		<pubDate>Wed, 04 May 2011 00:47:45 +0000</pubDate>
		<dc:creator>Henrique</dc:creator>
				<category><![CDATA[C]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.gilgalab.com.br/?p=232</guid>
		<description><![CDATA[As promissed, here is the second step on playing with the Python C API. If you haven't read the first post, I strongly suggest you to do so: Python C API - First Step This will be a much more exciting read with many new concepts. If you find something to be confusing or is [...]]]></description>
			<content:encoded><![CDATA[<p>As promissed, here is the second step on playing with the Python C API. If you haven't read the first post, I strongly suggest you to do so: <a href="http://www.gilgalab.com.br/2011/05/03/python-c-api-first-step/" target="_blank">Python C API - First Step</a></p>
<p>This will be a much more exciting read with many new concepts. If you find something to be confusing or is having a hard time understanding it, please let me know and we can discuss!</p>
<p>For this post I will show a code that does many things, such as:</p>
<ul>
<li> Look for the 'sys' module in the default loaded modules</li>
<li> Add a new path to the sys.path list in the sys module</li>
<li> Import a module wirtten by us </li>
<li> Access the members of the module that we loaded </li>
<li> Call a function from the module that we loaded </li>
<li> And more! </li>
</ul>
<p>I hope that from this introduction you feel excited about what is coming ahead!</p>
<p>So, let's start looking at the module we will import:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #483d8b;">''</span><span style="color: #483d8b;">' Save this code in a file called example.py '</span><span style="color: #483d8b;">''</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> doubleValue<span style="color: black;">&#40;</span>x<span style="color: black;">&#41;</span>:
    y = <span style="color: #ff4500;">2</span> <span style="color: #66cc66;">*</span> x
    <span style="color: #ff7700;font-weight:bold;">return</span> y
&nbsp;
myString = <span style="color: #483d8b;">&quot;Hello World!&quot;</span></pre></div></div>

<p>And finally the code that will do all those wonderful things mentioned in the list above:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/**
 * Save the code in a file called main.c
 * Compile with one of the following:
 *    gcc -Wall `python3.2-config --libs` `python3.2-config --include` main.c -o pyx
 *    gcc -Wall -lpthread -ldl -lutil -lm -lpython3.2mu -I/usr/include/python3.2mu main.c -o pyx
 * 
 * Run with: ./pyx
 * 
 * Use the code as you wish. If any help is needed, please let me know.
 * If you are going to republish this code somewhere, I would be grateful
 * if you can keep the credits of the code and/or a link to the original.
 *
 * Author: Henrique M. D.
 * Email: typoon at gmail dot com
 */</span>
&nbsp;
<span style="color: #339933;">#include &quot;Python.h&quot;</span>
<span style="color: #339933;">#include &lt;stdio.h&gt;</span>
<span style="color: #339933;">#include &lt;stdlib.h&gt;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> argc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span><span style="color: #339933;">**</span> argv<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
    <span style="color: #993333;">char</span> module_dir<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">255</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>name<span style="color: #339933;">;</span>
    <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>str<span style="color: #339933;">;</span>
    <span style="color: #666666; font-style: italic;">//wchar_t *module_path;</span>
    PyObject <span style="color: #339933;">*</span>poModule<span style="color: #339933;">;</span>
    PyObject <span style="color: #339933;">*</span>poDictModule<span style="color: #339933;">;</span>
    PyObject <span style="color: #339933;">*</span>poKey<span style="color: #339933;">;</span>
    PyObject <span style="color: #339933;">*</span>poValue<span style="color: #339933;">;</span>
    PyObject <span style="color: #339933;">*</span>poString<span style="color: #339933;">;</span>
    PyObject <span style="color: #339933;">*</span>poSys<span style="color: #339933;">;</span>
    PyObject <span style="color: #339933;">*</span>poList<span style="color: #339933;">;</span>
    PyObject <span style="color: #339933;">*</span>poListItem<span style="color: #339933;">;</span>
    PyObject <span style="color: #339933;">*</span>poPath<span style="color: #339933;">;</span>
    PyObject <span style="color: #339933;">*</span>poMyString<span style="color: #339933;">;</span>
    PyObject <span style="color: #339933;">*</span>poDoubleValue<span style="color: #339933;">;</span>
    PyObject <span style="color: #339933;">*</span>poResult<span style="color: #339933;">;</span>
    Py_ssize_t size<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">/* Start Part 1 */</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// This is the path where our .py scripts are. We will need to</span>
    <span style="color: #666666; font-style: italic;">// add this path to the sys.path list later on prior to loading</span>
    <span style="color: #666666; font-style: italic;">// it. If we don't do that, Python won't be able to load our script</span>
    <span style="color: #666666; font-style: italic;">// as it won't find it.</span>
    <span style="color: #666666; font-style: italic;">// Change this path accordingly to your setup</span>
    memset<span style="color: #009900;">&#40;</span>module_dir<span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">,</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span>module_dir<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    sprintf<span style="color: #009900;">&#40;</span>module_dir<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;/home/gilgamesh/codes/Pyx/scripts&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    Py_Initialize<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    poDictModule <span style="color: #339933;">=</span> PyImport_GetModuleDict<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    poString <span style="color: #339933;">=</span> PyUnicode_FromString<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;sys&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    poSys <span style="color: #339933;">=</span> PyDict_GetItem<span style="color: #009900;">&#40;</span>poDictModule<span style="color: #339933;">,</span> poString<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    Py_DECREF<span style="color: #009900;">&#40;</span>poString<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// refcount = 0, it can be freed now</span>
&nbsp;
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>poSys <span style="color: #339933;">==</span> NULL<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Cannot find the sys item in the dictionary. Aborting...<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>PyModule_Check<span style="color: #009900;">&#40;</span>poSys<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;This is not the sys module. Leaving...<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    poDictModule <span style="color: #339933;">=</span> PyModule_GetDict<span style="color: #009900;">&#40;</span>poSys<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    poList <span style="color: #339933;">=</span> PyDict_GetItemString<span style="color: #009900;">&#40;</span>poDictModule<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;path&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>PyList_Check<span style="color: #009900;">&#40;</span>poList<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;This is not the path list. Aborting...<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Path list before:<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> PyList_Size<span style="color: #009900;">&#40;</span>poList<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        poListItem <span style="color: #339933;">=</span> PyList_GetItem<span style="color: #009900;">&#40;</span>poList<span style="color: #339933;">,</span> i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>PyUnicode_Check<span style="color: #009900;">&#40;</span>poListItem<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>value <span style="color: #339933;">=</span> PyBytes_AsString<span style="color: #009900;">&#40;</span>PyUnicode_AsEncodedString<span style="color: #009900;">&#40;</span>poListItem<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;utf-8&quot;</span><span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Error&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\t</span>Value [%d] = %s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> i<span style="color: #339933;">,</span> value<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    poPath <span style="color: #339933;">=</span> PyUnicode_FromString<span style="color: #009900;">&#40;</span>module_dir<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    PyList_Append<span style="color: #009900;">&#40;</span>poList<span style="color: #339933;">,</span> poPath<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    Py_DECREF<span style="color: #009900;">&#40;</span>poPath<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Path list after:<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> PyList_Size<span style="color: #009900;">&#40;</span>poList<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        poListItem <span style="color: #339933;">=</span> PyList_GetItem<span style="color: #009900;">&#40;</span>poList<span style="color: #339933;">,</span> i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>PyUnicode_Check<span style="color: #009900;">&#40;</span>poListItem<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>value <span style="color: #339933;">=</span> PyBytes_AsString<span style="color: #009900;">&#40;</span>PyUnicode_AsEncodedString<span style="color: #009900;">&#40;</span>poListItem<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;utf-8&quot;</span><span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Error&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\t</span>Value [%d] = %s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> i<span style="color: #339933;">,</span> value<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">/* End Part 1 */</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">/* Start Part 2 */</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Here we will import our script. It is called example.py</span>
    <span style="color: #666666; font-style: italic;">// We just pass the name of the module without the .py as the</span>
    <span style="color: #666666; font-style: italic;">// Python interpreter knows that it should look for the file</span>
    <span style="color: #666666; font-style: italic;">// example.py</span>
    poModule <span style="color: #339933;">=</span> PyImport_ImportModule<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;example&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>poModule <span style="color: #339933;">==</span> NULL<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Error importing module<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        PyErr_Print<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Module imported succesfully!<span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    poDictModule <span style="color: #339933;">=</span> PyModule_GetDict<span style="color: #009900;">&#40;</span>poModule<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    size <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>PyDict_Next<span style="color: #009900;">&#40;</span>poDictModule<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>size<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>poKey<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>poValue<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        name <span style="color: #339933;">=</span> PyBytes_AsString<span style="color: #009900;">&#40;</span>PyUnicode_AsEncodedString<span style="color: #009900;">&#40;</span>poKey<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;utf-8&quot;</span><span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Error&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Type: %s - Symbol name: %s <span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>poValue<span style="color: #339933;">-&gt;</span>ob_type<span style="color: #339933;">-&gt;</span>tp_name<span style="color: #339933;">,</span> name<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Get the objects of the symbols we defined in our script    </span>
    poMyString <span style="color: #339933;">=</span> PyDict_GetItemString<span style="color: #009900;">&#40;</span>poDictModule<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;myString&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>poMyString<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>PyUnicode_Check<span style="color: #009900;">&#40;</span>poMyString<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            str <span style="color: #339933;">=</span> PyBytes_AsString<span style="color: #009900;">&#40;</span>PyUnicode_AsEncodedString<span style="color: #009900;">&#40;</span>poMyString<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;utf-8&quot;</span><span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Error&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;myString value is: %s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> str<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #b1b100;">else</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;myString is not a PyUnicode object. Are you messing up with the script?<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #b1b100;">else</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Symbol 'myString' not found...<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    poDoubleValue <span style="color: #339933;">=</span> PyDict_GetItemString<span style="color: #009900;">&#40;</span>poDictModule<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;doubleValue&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>poDoubleValue<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>PyFunction_Check<span style="color: #009900;">&#40;</span>poDoubleValue<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            poResult <span style="color: #339933;">=</span> PyObject_CallFunction<span style="color: #009900;">&#40;</span>poDoubleValue<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;i&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;doubleValue(2) = %ld<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> PyLong_AsLong<span style="color: #009900;">&#40;</span>poResult<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            Py_DECREF<span style="color: #009900;">&#40;</span>poResult<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #b1b100;">else</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;doubleValue is not a PyFunction object. Are you messing up with the script?<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #b1b100;">else</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Symbol 'doubleValue' not found...<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    Py_Finalize<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">/* End Part 2 */</span>
&nbsp;
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>I will not repeat myself about things that have already been explained in the first post, so I will just give an overview on what is happening here.</p>
<p>This code will import a Python module (a script written by us), print the value of the variable 'myString' that is declared in the script and execute the function 'doubleValue' that (as the name suggests) takes one integer argument, multiplies it by 2 and returns the result.</p>
<p>In order to achieve this, we need some preparation.</p>
<p>First, for Python to be able to find our module, we need to first provide it with the path to where our script is. This is what 'Part One' in the code is all about.</p>
<p>When one wants to import a module, the Python interpreter will check all the paths defined in the list "sys.path" for the module to be imported. If the module is found, it is then loaded otherwise the interpreter will throw an error about the module not being found.</p>
<p>As our module will be in a place different than the default places that python looks for, we need to add this path to the list of module paths.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">    poDictModule <span style="color: #339933;">=</span> PyImport_GetModuleDict<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    poString <span style="color: #339933;">=</span> PyUnicode_FromString<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;sys&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    poSys <span style="color: #339933;">=</span> PyDict_GetItem<span style="color: #009900;">&#40;</span>poDictModule<span style="color: #339933;">,</span> poString<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    Py_DECREF<span style="color: #009900;">&#40;</span>poString<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// refcount = 0, it can be freed now</span></pre></div></div>

<p>First, we grab the sys.modules dictionary so we can navigate later to the sys module and grab the path list.</p>
<p>We then create a PyUnicode representing the string "sys" that will be used to search for the "sys" module in the dictionary.</p>
<p>PyDict_GetItem() will two arguments: the dictionary we want to get an item from, and a PyObject with the string (a PyUnicode) representing the key in the dictionary. It then returns a PyObject* of the item associated with that key.</p>
<p>After we have our item, we decrement the reference count of 'poString' so it can be free()'d by the system. I will talk about refcounts in another post that is on its way, so don't worry too much about it for now.</p>
<p>At this point we have the module 'sys' in the poSys variable, and can finally go ahead to grab its dictionary and finding the 'path' list in it.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">    poDictModule <span style="color: #339933;">=</span> PyModule_GetDict<span style="color: #009900;">&#40;</span>poSys<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    poList <span style="color: #339933;">=</span> PyDict_GetItemString<span style="color: #009900;">&#40;</span>poDictModule<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;path&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This is the other way of getting an item from the dictionary. Instead of having all the trouble of creating a PyUnicode object, we can use PyDict_GetItemString() to get the item identified by the key passed as a char*.<br />
Not much new stuff here, we grab the dictionary for the "sys" module and then grab the "path" list from it.<br />
I know that "sys.path" is a list, because it is documented in the Python documentation somewhere (don't recall where thou).<br />
So now have the sys.path list in the 'poList' variable.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Path list before:<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> PyList_Size<span style="color: #009900;">&#40;</span>poList<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        poListItem <span style="color: #339933;">=</span> PyList_GetItem<span style="color: #009900;">&#40;</span>poList<span style="color: #339933;">,</span> i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>PyUnicode_Check<span style="color: #009900;">&#40;</span>poListItem<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>value <span style="color: #339933;">=</span> PyBytes_AsString<span style="color: #009900;">&#40;</span>PyUnicode_AsEncodedString<span style="color: #009900;">&#40;</span>poListItem<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;utf-8&quot;</span><span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Error&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\t</span>Value [%d] = %s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> i<span style="color: #339933;">,</span> value<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Here we are just printing all the items in the sys.path list. Prior to this point one can see that I have made all the checks to make sure that poList is really a PyList and that we can access it as such.</p>
<p>The sys.path list is a list of Strings, so it is okay to just go ahead and convert each item (that we retrieved using PyList_GetItem()) to a char* and then print it out.</p>
<p>An equivalent code in Python to do this would be:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">sys</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">print</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">sys</span>.<span style="color: black;">path</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Now we want to add the diretory where our module will be</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">    poPath <span style="color: #339933;">=</span> PyUnicode_FromString<span style="color: #009900;">&#40;</span>module_dir<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    PyList_Append<span style="color: #009900;">&#40;</span>poList<span style="color: #339933;">,</span> poPath<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    Py_DECREF<span style="color: #009900;">&#40;</span>poPath<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>As we are working with a list of PyUnicode (strings), we need to create a PyObject that represents our path as a PyUnicode, so again we are using PyUnicode_FromString() for this.</p>
<p>After that, we simply append the new path to the list, and again decremet the refcount of the recently created PyObject to make sure it will be cleaned up by the interpreter when it is time.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Path list after:<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> PyList_Size<span style="color: #009900;">&#40;</span>poList<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        poListItem <span style="color: #339933;">=</span> PyList_GetItem<span style="color: #009900;">&#40;</span>poList<span style="color: #339933;">,</span> i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>PyUnicode_Check<span style="color: #009900;">&#40;</span>poListItem<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>value <span style="color: #339933;">=</span> PyBytes_AsString<span style="color: #009900;">&#40;</span>PyUnicode_AsEncodedString<span style="color: #009900;">&#40;</span>poListItem<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;utf-8&quot;</span><span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Error&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\t</span>Value [%d] = %s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> i<span style="color: #339933;">,</span> value<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span></pre></div></div>

<p>Print the list again, to prove that our path is now in the sys.path list! :D</p>
<p>Great! Up to this point we saw some new functions and learned some cool stuff on how to handle a list and repracticed handling dictionaries.</p>
<p>What we want to do now is load our module, print all its dictionary entries, access its 'myString' member and call its 'doubleValue' function.<br />
All this things are identified in the code as Part 2.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">    <span style="color: #666666; font-style: italic;">// Here we will import our script. It is called example.py</span>
    <span style="color: #666666; font-style: italic;">// We just pass the name of the module without the .py as the</span>
    <span style="color: #666666; font-style: italic;">// Python interpreter knows that it should look for the file</span>
    <span style="color: #666666; font-style: italic;">// example.py</span>
    poModule <span style="color: #339933;">=</span> PyImport_ImportModule<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;example&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>I guess the comment in this part says it all. Just to make sure, the script presented in the begining of this post should be saved in a file 'example.py' for this to work. If you have saved it in a file with a different name, just make the changes here :)</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Module imported succesfully!<span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    poDictModule <span style="color: #339933;">=</span> PyModule_GetDict<span style="color: #009900;">&#40;</span>poModule<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    size <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>PyDict_Next<span style="color: #009900;">&#40;</span>poDictModule<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>size<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>poKey<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>poValue<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        name <span style="color: #339933;">=</span> PyBytes_AsString<span style="color: #009900;">&#40;</span>PyUnicode_AsEncodedString<span style="color: #009900;">&#40;</span>poKey<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;utf-8&quot;</span><span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Error&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Type: %s - Symbol name: %s <span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>poValue<span style="color: #339933;">-&gt;</span>ob_type<span style="color: #339933;">-&gt;</span>tp_name<span style="color: #339933;">,</span> name<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The module was succesfully imported, we get its dictionary and start printing everything on it!</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">    poMyString <span style="color: #339933;">=</span> PyDict_GetItemString<span style="color: #009900;">&#40;</span>poDictModule<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;myString&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>poMyString<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>PyUnicode_Check<span style="color: #009900;">&#40;</span>poMyString<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            str <span style="color: #339933;">=</span> PyBytes_AsString<span style="color: #009900;">&#40;</span>PyUnicode_AsEncodedString<span style="color: #009900;">&#40;</span>poMyString<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;utf-8&quot;</span><span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Error&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;myString value is: %s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> str<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #b1b100;">else</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;myString is not a PyUnicode object. Are you messing up with the script?<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #b1b100;">else</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Symbol 'myString' not found...<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span></pre></div></div>

<p>We retrieve the object that refers to the 'myString' variable in our Python code. If the symbol 'myString' is not present in the dictionary, the function PyDict_GetItemString() will return NULL, so that is why we check to see if there is anything in the poMyString variable. After that, we just want to make sure it is a PyUnicode object, so we can print its value. The printing part is pretty much the same thing we have been doing for every other PyUnicode.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">    poDoubleValue <span style="color: #339933;">=</span> PyDict_GetItemString<span style="color: #009900;">&#40;</span>poDictModule<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;doubleValue&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>poDoubleValue<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>PyFunction_Check<span style="color: #009900;">&#40;</span>poDoubleValue<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            poResult <span style="color: #339933;">=</span> PyObject_CallFunction<span style="color: #009900;">&#40;</span>poDoubleValue<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;i&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;doubleValue(2) = %ld<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> PyLong_AsLong<span style="color: #009900;">&#40;</span>poResult<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            Py_DECREF<span style="color: #009900;">&#40;</span>poResult<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #b1b100;">else</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;doubleValue is not a PyFunction object. Are you messing up with the script?<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #b1b100;">else</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Symbol 'doubleValue' not found...<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span></pre></div></div>

<p>Now we retrieve the object that refers to the function 'myDouble' that we declared in the script. So far, this is pretty much the same thing we have been doing all along. After that we check to make sure that what we got is really a function, and then the interesting part!<br />
PyObject_CallFunction() is one of the many ways to execute a function. Let's have a look at the prototype for PyObject_CallFunction() then:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">PyObject<span style="color: #339933;">*</span> PyObject_CallFunction<span style="color: #009900;">&#40;</span>PyObject <span style="color: #339933;">*</span>callable<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>format<span style="color: #339933;">,</span> ...<span style="color: #009900;">&#41;</span></pre></div></div>

<p>Let's talk about the arguments first.<br />
<b>callable</b> is the PyObject that represents the function we want to call.</p>
<p><b>format</b> just like printf() is a function that receives a 'format' parameter, this parameter works the same way, the difference is that the characters used to represent thigs are different. This string will have the format of what kind of parameters will come right after. For our code, we have PyObject_CallFunction(poDoubleValue, "i", 2) - Here what happens is, the parameter right after the format is taken as an int, because the format string is "i". If the format string was "iii", we would need to pass 3 parameters, like this: PyObject_CallFunction(poDoubleValue, "iii", 2,3,4);</p>
<p><b>...</b> all other parameters that are needed depending on the 'format' string.</p>
<p>The "format" parameter shall reflect as many parameters as the function is expecting.</p>
<p>After calling the function, simply print the result (which is an int, treated as a PyLong in Python).<br />
We decrement the reference count for cleanup.</p>
<p>After all this, we just execute a PyFinalize() to finish the interpreter, and we are done!</p>
<h4>References:</h4>
<p><a href="http://docs.python.org/py3k/c-api/index.html" target="blank">Python/C API Reference Manual</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.gilgalab.com.br/2011/05/03/python-c-api-second-step/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Python C API &#8211; First Step</title>
		<link>http://www.gilgalab.com.br/2011/05/03/python-c-api-first-step/</link>
		<comments>http://www.gilgalab.com.br/2011/05/03/python-c-api-first-step/#comments</comments>
		<pubDate>Tue, 03 May 2011 12:27:10 +0000</pubDate>
		<dc:creator>Henrique</dc:creator>
				<category><![CDATA[C]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.gilgalab.com.br/?p=209</guid>
		<description><![CDATA[I am once again in that time of the year where I start to look back at projects I started and did not finish. I am trying to make a personal commitment to select one or two of those and have them rolling. One of these projects involve embedding Python into it to make it [...]]]></description>
			<content:encoded><![CDATA[<p>I am once again in that time of the year where I start to look back at projects I started and did not finish. I am trying to make a personal commitment to select one or two of those and have them rolling. One of these projects involve embedding Python into it to make it extensible. As it has been a long time since I started this project, I barely remember how that stuff works, so I am once again tackling the problem to see where I can get.</p>
<p>I plan to make this post a little bit simple (but can't guarantee I will be able to), showing some code and explaining parts of it. Where I see the need (and have the knowledge to do so) I will try to discuss a little bit about how certain thing work.</p>
<p>For everything discussed here, I will be using Python 3.2. It is possible some of this stuff won't work with Python 2.x but will probably work fine with Python 3.1.</p>
<p>So, let's start with a simple program that will just initialize Python and list all modules that are loaded as soon as the initialization is finished.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &quot;Python.h&quot;</span>
<span style="color: #339933;">#include &lt;stdio.h&gt;</span>
<span style="color: #339933;">#include &lt;stdlib.h&gt;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> argc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span><span style="color: #339933;">**</span> argv<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>name<span style="color: #339933;">;</span>
    PyObject <span style="color: #339933;">*</span>dictModule<span style="color: #339933;">;</span>
    Py_ssize_t size<span style="color: #339933;">;</span>
    PyObject <span style="color: #339933;">*</span>poKey<span style="color: #339933;">;</span>
    PyObject <span style="color: #339933;">*</span>poValue<span style="color: #339933;">;</span>
&nbsp;
    Py_Initialize<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    dictModule <span style="color: #339933;">=</span> PyImport_GetModuleDict<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    size <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>PyDict_Next<span style="color: #009900;">&#40;</span>dictModule<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>size<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>poKey<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>poValue<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        name <span style="color: #339933;">=</span> PyBytes_AsString<span style="color: #009900;">&#40;</span>PyUnicode_AsEncodedString<span style="color: #009900;">&#40;</span>poKey<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;utf-8&quot;</span><span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Error&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Type: %s - Name: %s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>poValue<span style="color: #339933;">-&gt;</span>ob_type<span style="color: #339933;">-&gt;</span>tp_name<span style="color: #339933;">,</span> name<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    Py_Finalize<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>To compile this code, you can use the following command (Considering you saved the source in a file called main.c):<br />
<span class="command">gcc -Wall `python3.2-config --include` `python3.2-config --libs` -o pyx main.c</span></p>
<p>If python3.2-config is not available at you platform, this is what it expands to in my computer:<br />
<span class="command">gcc -Wall -lpthread -ldl -lutil -lm -lpython3.2mu -I/usr/include/python3.2mu -I/usr/include/python3.2mu -o pyx main.c</span></p>
<p>It is up to you to figure out the include paths :) If you have trouble, let me know in the comments.</p>
<p>Since this is a new topic, I will talk a little bit about the new types we see: PyObject and Py_ssize_t.</p>
<p><b>Py_ssize_t</b> is a typedef to ssize_t or to a long int. It is recommended to use Py_ssize_t as it might change in the future and this guarantees compatibility.</p>
<p><b>PyObject</b> is an opaque type that seems to be the base to pretty much everything in Python. A module, a dictionary, an object, a function... they are all represented by a PyObject. There are functions and/or macros that can be used to identify what kind of information is stored in a PyObject. For example, if one wants to know if the PyObject in hand is a dictionary, the macro PyDict_Check(PyObject *p) can be used. This macro returns true if the PyObject 'p' is a dictionary.</p>
<p>I won't be discussing much of the inner workings of PyObject, because that would take a long time, and I am still not too familiar with that yet (Hopefully I will have a pot in the future just to discuss it). I guess it is enough to know that most functions that handle a python object will deal with this structure.</p>
<p>PyInitialize() simply initializes the interpreter and loads everything that python needs. I couldn't express this better than the documentation, so let me quote it:</p>
<blockquote><p>
Initialize the Python interpreter. In an application embedding Python, this should be called before using any other Python/C API functions; with the exception of Py_SetProgramName() and Py_SetPath(). This initializes the table of loaded modules (sys.modules), and creates the fundamental modules builtins, __main__ and sys. It also initializes the module search path (sys.path). It does not set sys.argv; use PySys_SetArgvEx() for that. This is a no-op when called for a second time (without calling Py_Finalize() first). There is no return value; it is a fatal error if the initialization fails.
</p></blockquote>
<p>It is safe to ignore the information regarding other functions for now.</p>
<p>So, as soon as Python has been initialized, I was curious about which modules were loaded to see if they would match what the documentation mentioned. Digging into it, I found the function PyImport_GetModuleDict() that will return the dictionary of the default loaded module sys.modules. With this in hand I am able to iterate through the dictionary and print everything that is available in it.</p>
<p>In order to navigate through the dictionary, we can use the function PyDict_Next() which has the following prototype:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">int</span> PyDict_Next<span style="color: #009900;">&#40;</span>PyObject <span style="color: #339933;">*</span>p<span style="color: #339933;">,</span> Py_ssize_t <span style="color: #339933;">*</span>ppos<span style="color: #339933;">,</span> PyObject <span style="color: #339933;">**</span>pkey<span style="color: #339933;">,</span> PyObject <span style="color: #339933;">**</span>pvalue<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p><b>PyObject *p</b> - The dictionary we want to iterate through.<br />
<b>Py_ssize_t *ppos</b> - This will tell the offset inside the dictionary where the current data is found. This value HAS to be initialized to 0 prior to calling this function and should not be changed inside the loop calling PyDict_Next (as this is the variable that keeps track of the offset being used by the function).<br />
<b>PyObject **pkey</b> - This will be a string object containing the name of the dictionary entry (the key of the dictionary, which represents the symbol being analyzed).<br />
<b>PyObject **pvalue</b> - The value to which the current key refers to. This can be anything: a module, another dictionary, a function, a long, a string and so on...</p>
<p>Strings in Python are all Unicode and are represented by a PyObject as well. For that reason, in order to print the string value to the terminal, we need to first convert the PyUnicode object to a PyBytes object which can then be converted to a regular string (char *). This is what is happening in the following line:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">name <span style="color: #339933;">=</span> PyBytes_AsString<span style="color: #009900;">&#40;</span>PyUnicode_AsEncodedString<span style="color: #009900;">&#40;</span>poKey<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;utf-8&quot;</span><span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Error&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>When trying to determine the type of the PyObject I could not find a function that would return a string telling the type, so I started analyzing the PyObject structure and found a field tp_name (which I presume means "type name") inside the ob_type structure contained in it. I guess accessing PyObject's members directly isn't recommended, but as this is being used for learning purposes I might be forgiven.</p>
<p>After everything is completed, we just finalize the Python interpreter by calling PyFinalize(). This will make sure Python does its cleanup and frees all memory it was using.</p>
<p>As stated in the post title, this is just the first step playing with the API. I plan to show some more code in the posts to follow, where we will be able to execute python code without interacting with the interpreter, and a code to import a Python module (a .py file with Python code) and then interact with the interpreter, by reading the data in the file and executing its functions.</p>
<p>For now, this is it!</p>
<h4>References:</h4>
<p><a href="http://docs.python.org/py3k/c-api/index.html" target="blank">Python/C API Reference Manual</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.gilgalab.com.br/2011/05/03/python-c-api-first-step/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Cheating on Windows&#8217; Minesweeper</title>
		<link>http://www.gilgalab.com.br/2011/03/26/cheating-on-windows-minesweeper/</link>
		<comments>http://www.gilgalab.com.br/2011/03/26/cheating-on-windows-minesweeper/#comments</comments>
		<pubDate>Sun, 27 Mar 2011 01:11:35 +0000</pubDate>
		<dc:creator>Henrique</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.gilgalab.com.br/?p=142</guid>
		<description><![CDATA[Minesweeper? Sounds kinda lame right? Well, in fact it is pretty lame to cheat on minesweeper but the steps needed to achieve it are fun. Sometime in the past I was a little bored and decided I wanted to try to write a small program to play minesweeper, so I thought, 'Ok, how to approach [...]]]></description>
			<content:encoded><![CDATA[<p>Minesweeper? Sounds kinda lame right? Well, in fact it is pretty lame to cheat on minesweeper but the steps needed to achieve it are fun.</p>
<p>Sometime in the past I was a little bored and decided I wanted to try to write a small program to play minesweeper, so I thought, 'Ok, how to approach that?'. I decided the easiest way would be to check the state of the current board by looking at the process memory, and from there develop an algorithm to decide the next move and than (in some way I did not know yet at the time), have the mouse click the right place or send a message to the window telling what box to open.</p>
<p>Turns out I never really completed such program to play minesweeper and instead I developed a small program that would read the process memory, figure out where all bombs were and mark them all automatically so I could always win in 1 click!</p>
<p>Guess this pretty much describes what is going to be analyzed from here on. We will figure out how to dump the memory of the minesweeper process, deduce how the game data is structured in memory, find out what represents the numbers and what represents the bombs and finally from that memory dump we will write it all back to the process memory and have the board refreshed!</p>
<p>I hope it sounded complicated (because in fact it is pretty simple stuff).</p>
<p>Before we start, I might say I am not familiar with Windows development neither am familiar with the rules used for Windows software development so my code might look a little odd for those that are used to such rules. If you spot any errors, please let me know in the comments ;D</p>
<p>So, when we open minesweeper, if we check the task list (ctrl+esc) we will see that the process name is "winmine.exe" (in fact this is the image name, but that will suit us for now). That is pretty much all the information we need to be able to retrieve the process memory so we can start analyzing. Take a look at the following code:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">&nbsp;
<span style="color: #339933;">#include &lt;windows.h&gt;</span>
<span style="color: #339933;">#include &quot;Tlhelp32.h&quot;</span>
<span style="color: #339933;">#include &lt;stdio.h&gt;</span>
<span style="color: #339933;">#include &lt;string.h&gt;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> argc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">**</span>argv<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
&nbsp;
    HANDLE snapshot<span style="color: #339933;">;</span>
    PROCESSENTRY32 pe<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Take snapshot of all processes</span>
    snapshot <span style="color: #339933;">=</span> CreateToolhelp32Snapshot<span style="color: #009900;">&#40;</span>TH32CS_SNAPPROCESS<span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>snapshot <span style="color: #339933;">==</span> INVALID_HANDLE_VALUE<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Error creating snapshot<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    pe.<span style="color: #202020;">dwSize</span> <span style="color: #339933;">=</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span>PROCESSENTRY32<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>Process32First<span style="color: #009900;">&#40;</span>snapshot<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>pe<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Error obtaining first process from the list<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #b1b100;">do</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> pe.<span style="color: #202020;">szExeFile</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>Process32Next<span style="color: #009900;">&#40;</span>snapshot<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>pe<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    getchar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This code will list all the processes currently running in the machine and their respective modules. We will not go into details on how Windows manages its processes nor how they are organized. For our purpose here all we need to know is that a process can have many modules, and one of those modules refer to the binary we want to deal with (in this case the minesweeper).</p>
<p>We use the PROCESS_QUERY_INFORMATION and PROCESS_VM_READ permissions so we can use GetModuleBaseName function to list all the modules in the processes. The PROCESS_VM_WRITE permission is there because in the future we will want to write to the memory region so we need that permission.</p>
<p>Great, now that we have all the processes listed, we need to filter to find our minesweeper process and then start the real fun part!</p>
<p>Let's make some changes to the code, so we can find the Minesweeper process and read its memory:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;windows.h&gt;</span>
<span style="color: #339933;">#include &quot;Tlhelp32.h&quot;</span>
<span style="color: #339933;">#include &lt;stdio.h&gt;</span>
<span style="color: #339933;">#include &lt;string.h&gt;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">/*
 * @param name - Name of the process we are looking for
 * @param prcs - The id of the process to list the modules
 * @param hnd - The handle to the process that contains the module we want
 * @param baseAddress - The base address of the module
 * @param baseSize - How many bytes to read from baseAddress
 */</span>
<span style="color: #993333;">int</span> findModule<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">*</span>name<span style="color: #339933;">,</span> DWORD prcs<span style="color: #339933;">,</span> HANDLE <span style="color: #339933;">*</span>hnd<span style="color: #339933;">,</span> DWORD <span style="color: #339933;">**</span>baseAddress<span style="color: #339933;">,</span> DWORD <span style="color: #339933;">*</span>baseSize<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">int</span> perm<span style="color: #339933;">;</span>
    HANDLE snapshot<span style="color: #339933;">;</span>
    MODULEENTRY32 me<span style="color: #339933;">;</span>
&nbsp;
    perm <span style="color: #339933;">=</span> PROCESS_VM_READ <span style="color: #339933;">|</span> PROCESS_VM_WRITE <span style="color: #339933;">|</span> PROCESS_QUERY_INFORMATION<span style="color: #339933;">;</span>
    <span style="color: #339933;">*</span>hnd <span style="color: #339933;">=</span> OpenProcess<span style="color: #009900;">&#40;</span>perm<span style="color: #339933;">,</span> FALSE<span style="color: #339933;">,</span> prcs<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>hnd <span style="color: #339933;">==</span> NULL<span style="color: #009900;">&#41;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
&nbsp;
    snapshot <span style="color: #339933;">=</span> CreateToolhelp32Snapshot<span style="color: #009900;">&#40;</span>TH32CS_SNAPMODULE<span style="color: #339933;">,</span> prcs<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>snapshot <span style="color: #339933;">==</span> INVALID_HANDLE_VALUE<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    me.<span style="color: #202020;">dwSize</span> <span style="color: #339933;">=</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span>MODULEENTRY32<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>Module32First<span style="color: #009900;">&#40;</span>snapshot<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>me<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #b1b100;">do</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>_stricmp<span style="color: #009900;">&#40;</span>name<span style="color: #339933;">,</span> me.<span style="color: #202020;">szModule</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #339933;">*</span>baseAddress <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>DWORD <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>me.<span style="color: #202020;">modBaseAddr</span><span style="color: #339933;">;</span>
            <span style="color: #339933;">*</span>baseSize <span style="color: #339933;">=</span> me.<span style="color: #202020;">modBaseSize</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>Module32Next<span style="color: #009900;">&#40;</span>snapshot<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>me<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> argc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">**</span>argv<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
    DWORD <span style="color: #339933;">*</span>baseAddress<span style="color: #339933;">;</span>
    DWORD baseSize<span style="color: #339933;">;</span>
    HANDLE snapshot<span style="color: #339933;">;</span>
    HANDLE hnd<span style="color: #339933;">;</span>
    PROCESSENTRY32 pe<span style="color: #339933;">;</span>
    SIZE_T bytesRead<span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span><span style="color: #339933;">*</span> memory<span style="color: #339933;">;</span>
    FILE <span style="color: #339933;">*</span>f<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>argc <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">3</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Use: %s &lt;executable.exe&gt; &lt;dump_file.txt&gt;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> argv<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Example: %s winmine.exe mem_dump1.txt<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> argv<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Take snapshot of all processes</span>
    snapshot <span style="color: #339933;">=</span> CreateToolhelp32Snapshot<span style="color: #009900;">&#40;</span>TH32CS_SNAPPROCESS<span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>snapshot <span style="color: #339933;">==</span> INVALID_HANDLE_VALUE<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Error creating snapshot<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    pe.<span style="color: #202020;">dwSize</span> <span style="color: #339933;">=</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span>PROCESSENTRY32<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>Process32First<span style="color: #009900;">&#40;</span>snapshot<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>pe<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Error obtaining first process from the list<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    memory <span style="color: #339933;">=</span> NULL<span style="color: #339933;">;</span>
    <span style="color: #b1b100;">do</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>_stricmp<span style="color: #009900;">&#40;</span>pe.<span style="color: #202020;">szExeFile</span><span style="color: #339933;">,</span> argv<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>findModule<span style="color: #009900;">&#40;</span>argv<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> pe.<span style="color: #202020;">th32ProcessID</span><span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>hnd<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>baseAddress<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>baseSize<span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
            <span style="color: #009900;">&#123;</span>
                memory <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>malloc<span style="color: #009900;">&#40;</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span>baseSize<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>ReadProcessMemory<span style="color: #009900;">&#40;</span>hnd<span style="color: #339933;">,</span> baseAddress<span style="color: #339933;">,</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>memory<span style="color: #339933;">,</span> baseSize<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>bytesRead<span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
                <span style="color: #009900;">&#123;</span>
                    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Error reading process memory<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span>
                <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>Process32Next<span style="color: #009900;">&#40;</span>snapshot<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>pe<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>memory <span style="color: #339933;">!=</span> NULL<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>f <span style="color: #339933;">=</span> fopen<span style="color: #009900;">&#40;</span>argv<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;w+&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> NULL<span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Error creating file to dump memory<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        fprintf<span style="color: #009900;">&#40;</span>f<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Base address: %08X<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> baseAddress<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        fprintf<span style="color: #009900;">&#40;</span>f<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Base size: %d<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> baseSize<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        fprintf<span style="color: #009900;">&#40;</span>f<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Bytes read: %d<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> bytesRead<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        fprintf<span style="color: #009900;">&#40;</span>f<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        fprintf<span style="color: #009900;">&#40;</span>f<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;0x00000000: &quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> bytesRead<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #666666; font-style: italic;">//fwrite(&amp;memory[i], 1, 1, f);</span>
            fprintf<span style="color: #009900;">&#40;</span>f<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;%02X&quot;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>memory<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>i<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> <span style="color: #0000dd;">16</span> <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
            <span style="color: #009900;">&#123;</span>
                fwrite<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">,</span> f<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                fprintf<span style="color: #009900;">&#40;</span>f<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;0x%08X: &quot;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#40;</span>i<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
        fclose<span style="color: #009900;">&#40;</span>f<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Finished dumping memory. Check file %s&quot;</span><span style="color: #339933;">,</span> argv<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Good! This is then the source code to the program we will use to take all the memory dumps from the process we want to read.</p>
<p>Using it is pretty simple, just execute it on a command prompt passing as arguments the name of the process (the name shown in the "Image Name" column in the task manager) and the name of the file where the memory dump should be saved. E.g. <b>cheater.exe winmine.exe mem_dump1.txt</b></p>
<p>In order to figure out how the board is structured in memory, I will take 4 different memory dumps and compare them using a diff tool. That will show what has changed where.</p>
<p>Below are the screenshots of the board during each dump and their respective dumps:</p>
<table>
<tr>
<td><img src="/wp-content/uploads/2011/03/dump1.png" alt="Dump1" /></td>
<td><img src="/wp-content/uploads/2011/03/dump2.png" alt="Dump2" /></td>
<td><img src="/wp-content/uploads/2011/03/dump3.png" alt="Dump3" /></td>
</tr>
<tr>
<td><a href="/wp-content/uploads/2011/03/dump1.txt">Dump1.txt</a></td>
<td><a href="/wp-content/uploads/2011/03/dump2.txt">Dump2.txt</a></td>
<td><a href="/wp-content/uploads/2011/03/dump3.txt">Dump3.txt</a></td>
</tr>
</table>
<p>Because each dump is 300kb+ I will just post the parts that differ between the files during the explanation ahead, but the dumps above are the whole thing, so you can read them if you want to make your own comparison.</p>
<p>Dump1.txt shows the table in the Beginner level without any fields revealed. This is the dump we will use as base for the comparisons.</p>
<p>Dump2.txt shows the table in the Beginner level with one field opened on the third line and fourth column (check the picture above) with 3 seconds of gameplay (the picture is wrong because I was not fast enough to take the screenshot right after i took the memory dump).</p>
<p>Dump3.txt shows pretty much the same thing as Dump2.txt except that the time of gameplay is now 999 seconds.</p>
<p>The dumps are formated in the following way:</p>
<p>Number of bytes relative to the base address: byte0 byte1 byte2 byte3 ... byte15</p>
<p>So let's look at the differences between the two dumps:</p>
<p>0x00005160: 00 00 00 00 <span style="color: #00ff00; background-color: #000000;">00 00 00 00 00 00 00 00</span> 00 00 00 00 - Dump1<br />
0x00005160: 00 00 00 00 <span style="color: #00ff00; background-color: #000000;">01 00 00 00 00 00 00 00</span> 00 00 00 00 - Dump2<br />
0x00005160: 00 00 00 00 <span style="color: #00ff00; background-color: #000000;">01 00 00 00 01 00 00 00</span> 00 00 00 00 - Dump3</p>
<p>0x000053A0: 10 0F 0F 0F <span style="color: #ffff00; background-color: #000000;">0F</span> 0F 0F 0F 0F 0F 10 0F 0F 0F 0F 0F - Dump1<br />
0x000053A0: 10 0F 0F 0F <span style="color: #ffff00; background-color: #000000;">41</span> 0F 0F 0F 0F 0F 10 0F 0F 0F 0F 0F - Dump2<br />
0x000053A0: 10 0F 0F 0F <span style="color: #ffff00; background-color: #000000;">41</span> 0F 0F 0F 0F 0F 10 0F 0F 0F 0F 0F - Dump3</p>
<p>0x00005790: 00 00 00 00 00 00 00 00 01 00 00 00 <span style="color: #aaaaaa; background-color: #000000;">00 00 00 00</span> - Dump1<br />
0x000057A0: 47 00 00 00 <span style="color: #ff0000; background-color: #000000;">00</span> 00 00 00 00 00 00 00 00 00 00 00 - Dump1</p>
<p>0x00005790: 00 00 00 00 00 00 00 00 01 00 00 00 <span style="color: #aaaaaa; background-color: #000000;">03 00 00 00</span> - Dump2<br />
0x000057A0: 47 00 00 00 <span style="color: #ff0000; background-color: #000000;">01</span> 00 00 00 00 00 00 00 00 00 00 00 - Dump2</p>
<p>0x00005790: 00 00 00 00 00 00 00 00 01 00 00 00 <span style="color: #aaaaaa; background-color: #000000;">E7 03 00 00</span> - Dump3<br />
0x000057A0: 47 00 00 00 <span style="color: #ff0000; background-color: #000000;">01</span> 00 00 00 00 00 00 00 00 00 00 00 - Dump3</p>
<p>Those are all the differences that I could find using WinMerge (it is a diff tool to merge differences!!). </p>
<p>Let's look at the values in gray:</p>
<ul>
<li>For Dump1 it is 00 00 00 00, if we take that as an integer in decimal it means 0</li>
<li>For Dump2 it is 03 00 00 00, if we take that as an integer in decimal it means 3 (Bytes are in reverse order in memory, least significat bytes first)</li>
<li>For Dump3 it is E7 03 00 00, if we take that as an integer in decimal it means 999 (Read it as 03E7)</li>
</ul>
<p>Guess we found where the value of the time counter is stored huh? Dump3 was taken when the clock was at 999, while dump2 was taken at time 3!</p>
<p>The numbers in green I am still not able to tell what they mean, so for now I will just leave them alone.</p>
<p>Now we have two candidates to be the square we have opened in the board, being those the ones in red or the ones in yellow. It is impossible to tell only with these three dumps which one is it, so we will open some more fields to check.</p>
<p>At this point, I took the fourth dump (Dump4.txt), which shows the board as follows:</p>
<table>
<tr>
<td><img src="/wp-content/uploads/2011/03/dump4.png" /></td>
</tr>
<tr>
<td><a href="/wp-content/uploads/2011/03/dump4.txt">Dump4.txt</a></td>
</tr>
</table>
<p>So, let's compare Dump3 and Dump4:</p>
<p>0x000057A0: 47 00 00 00 <span style="color: #ff0000; background-color: #000000;">01</span> 00 00 00 00 00 00 00 00 00 00 00 - Dump3<br />
0x000057A0: 47 00 00 00 <span style="color: #ff0000; background-color: #000000;">03</span> 00 00 00 00 00 00 00 00 00 00 00 - Dump4</p>
<p>Cool! Only that one byte changed, and the value seems to be exactly the number of squares we have opened in the board!</p>
<p>Now, while comparing dump3 and dump4, here are the changes that have been found:</p>
<p><b>Dump3</b><br />
    0x00005320: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00<br />
    0x00005330: 0A 00 00 00 09 00 00 00 09 00 00 00 00 00 00 00<br />
    0x00005340: <span style="color: #ffffff; background-color: #000000;">10 10 10 10 10 10 10 10 10 10 10</span> 0F 0F 0F 0F 0F<br />
    0x00005350: 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F<br />
    0x00005360: <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F 0F 0F 0F 0F <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F<br />
    0x00005370: 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F<br />
    0x00005380: <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F 0F 0F 0F 0F <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F<br />
    0x00005390: 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F<br />
    0x000053A0: <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 41 0F 0F 0F 0F 0F <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F<br />
    0x000053B0: 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F<br />
    0x000053C0: <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 8F 0F 0F 8F 0F <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F<br />
    0x000053D0: 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F<br />
    0x000053E0: <span style="color: #ffffff; background-color: #000000;">10</span> 0F 8F 8F 0F 0F 8F 0F 0F 0F <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F<br />
    0x000053F0: 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F<br />
    0x00005400: <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F 0F 0F 0F 0F <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F<br />
    0x00005410: 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F</p>
<p><b>Dump4</b><br />
    0x00005320: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00<br />
    0x00005330: 0A 00 00 00 09 00 00 00 09 00 00 00 00 00 00 00<br />
    0x00005340: <span style="color: #ffffff; background-color: #000000;">10 10 10 10 10 10 10 10 10 10 10</span> 0F 0F 0F 0F 0F<br />
    0x00005350: 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F<br />
    0x00005360: <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F 0F 0F 0F 0F <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F<br />
    0x00005370: 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F<br />
    0x00005380: <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F 0F 0F 0F 0F <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F<br />
    0x00005390: 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F<br />
    0x000053A0: <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F <span style="color: #ff0000; background-color: #000000;">41</span> 0F 0F 0F 0F 0F <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F<br />
    0x000053B0: 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F<br />
    0x000053C0: <span style="color: #ffffff; background-color: #000000;">10</span> 0F <span style="color: #ff0000; background-color: #000000;">42</span> 0F 0F 8F 0F 0F 8F 0F <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F<br />
    0x000053D0: 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F<br />
    0x000053E0: <span style="color: #ffffff; background-color: #000000;">10</span> 0F 8F 8F 0F 0F 8F 0F 0F 0F <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F<br />
    0x000053F0: 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F<br />
    0x00005400: <span style="color: #ffffff; background-color: #000000;">10</span> <span style="color: #ff0000; background-color: #000000;">41</span> 0F 0F 0F 0F 0F 0F 0F 0F <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F<br />
    0x00005410: 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F</p>
<p>Looks like we found our board!</p>
<p>Let me put 32 bytes per line and add some more bytes to the listing, to make it easier to see!</p>
<p><b>Dump3</b><br />
    0x00005320: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0A 00 00 00 09 00 00 00 09 00 00 00 00 00 00 00<br />
    0x00005340: 10 10 10 10 10 10 10 10 10 10 10 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F<br />
    0x00005360: 10 0F 0F 0F 0F 0F 0F 0F 0F 0F 10 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F<br />
    0x00005380: 10 0F 0F 0F 0F 0F 0F 0F 0F 0F 10 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F<br />
    0x000053A0: 10 0F 0F 0F <span style="color: #ff0000; background-color: #000000;">41</span> 0F 0F 0F 0F 0F 10 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F<br />
    0x000053C0: 10 0F <span style="color: #ff0000; background-color: #000000;">0F</span> 0F 0F 8F 0F 0F 8F 0F 10 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F<br />
    0x000053E0: 10 0F 8F 8F 0F 0F 8F 0F 0F 0F 10 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F<br />
    0x00005400: 10 <span style="color: #ff0000; background-color: #000000;">0F</span> 0F 0F 0F 0F 0F 0F 0F 0F 10 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F<br />
    0x00005420: 10 0F 0F 0F 0F 8F 0F 0F 0F 0F 10 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F<br />
    0x00005440: 10 0F 0F 0F 0F 0F 8F 0F 0F 0F 10 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F<br />
    0x00005460: 10 8F 0F 0F 0F 0F 8F 0F 0F 8F 10 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F<br />
    0x00005480: 10 10 10 10 10 10 10 10 10 10 10 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F</p>
<p><b>Dump4</b><br />
    0x00005320: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 <span style="color: #00ff00; background-color: #000000;">0A 00 00 00</span> <span style="color: #ff0000; background-color: #000000;">09 00 00 00 09 00 00 00</span> 00 00 00 00<br />
    0x00005340: <span style="color: #ffffff; background-color: #000000;">10 10 10 10 10 10 10 10 10 10 10</span> 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F<br />
    0x00005360: <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F 0F 0F 0F 0F <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F - Line 1<br />
    0x00005380: <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F 0F 0F 0F 0F <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F - Line 2<br />
    0x000053A0: <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F <span style="color: #000000; background-color: #aaaaaa;">41</span> 0F 0F 0F 0F 0F <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F - Line 3<br />
    0x000053C0: <span style="color: #ffffff; background-color: #000000;">10</span> 0F <span style="color: #000000; background-color: #aaaaaa;">42</span> 0F 0F 8F 0F 0F 8F 0F <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F - Line 4<br />
    0x000053E0: <span style="color: #ffffff; background-color: #000000;">10</span> 0F 8F 8F 0F 0F 8F 0F 0F 0F <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F - Line 5<br />
    0x00005400: <span style="color: #ffffff; background-color: #000000;">10</span> <span style="color: #000000; background-color: #aaaaaa;">41</span> 0F 0F 0F 0F 0F 0F 0F 0F <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F - Line 6<br />
    0x00005420: <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 8F 0F 0F 0F 0F <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F - Line 7<br />
    0x00005440: <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F 8F 0F 0F 0F <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F - Line 8<br />
    0x00005460: <span style="color: #ffffff; background-color: #000000;">10</span> 8F 0F 0F 0F 0F 8F 0F 0F 8F <span style="color: #ffffff; background-color: #000000;">10</span> 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F - Line 9<br />
    0x00005480: <span style="color: #ffffff; background-color: #000000;">10 10 10 10 10 10 10 10 10 10 10</span> 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F</p>
<p>See? Looks like the board is surrounded by the byte 0x10. </p>
<p>The beginner board is a a 9x9 squares board and it has 10 bombs.</p>
<p>I guess we can say that the four bytes in green above represent the number of bombs (I think it is an integer), and the eight bytes in red represent the width and height of our board (2 separate integers).</p>
<p>Note inside the board at address 0x000053A4 there is a 0x41. So we have:</p>
<ul>
<li>The value in the third line and fourth column is 0x41, which is the number 1 in the board</li>
<li>The value at the fourth line and second column is 0x42, which is the number 2 in the board</li>
<li>The value at the sixth line and first column is 0x41, which again is the number 1 in the board</li>
</ul>
<p>Looks like it is safe to say (even thou we are going to test it later) that the values accepted here range from 0x41 to 0x48 for the numbers 1 to 8.</p>
<p>If we pay closer attention, the squares that we show opened in Dump4 used to have a value of <b>0x0F</b> in Dump3. In this latter dump, we also notice the value <b>0x8F</b> inside the board. Count how many of those 0x8F bytes we have inside the board and we get the value 10 which matches the numebr of bombs in the board.</p>
<p>Let's click one of those 0x8F squares to check if this is right:</p>
<p><image src="/wp-content/uploads/2011/03/dump4_bomb.png"></img></p>
<p>Yep, we got it right!</p>
<p>Looking at another dump I took, i noticed that the value <b>0x0E</b> is the one that represents the flag we place in the squares we think have bombs.</p>
<p>Based on this, I wrote the following program that will search for the board and mark all the squares that have bombs with the flag!</p>
<p>To execute the program, you will need to pass to it the name of the "Image Name" and the base address (which can be found in the dump files taken with the program presented before).</p>
<p>In order to find the board, it will look for a sequence of 5 bytes 0x10 in a row (which would indicate the beginning of the board). So here is the code:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;windows.h&gt;</span>
<span style="color: #339933;">#include &quot;Tlhelp32.h&quot;</span>
<span style="color: #339933;">#include &lt;stdio.h&gt;</span>
<span style="color: #339933;">#include &lt;string.h&gt;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">/*
 * @param name - Name of the process we are looking for
 * @param prcs - The id of the process to list the modules
 * @param hnd - The handle to the process that contains the module we want
 * @param baseAddress - The base address of the module
 * @param baseSize - How many bytes to read from baseAddress
 */</span>
<span style="color: #993333;">int</span> findModule<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">*</span>name<span style="color: #339933;">,</span> DWORD prcs<span style="color: #339933;">,</span> HANDLE <span style="color: #339933;">*</span>hnd<span style="color: #339933;">,</span> DWORD <span style="color: #339933;">**</span>baseAddress<span style="color: #339933;">,</span> DWORD <span style="color: #339933;">*</span>baseSize<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">int</span> perm<span style="color: #339933;">;</span>
    HANDLE snapshot<span style="color: #339933;">;</span>
    MODULEENTRY32 me<span style="color: #339933;">;</span>
&nbsp;
    perm <span style="color: #339933;">=</span> PROCESS_VM_READ <span style="color: #339933;">|</span> PROCESS_VM_WRITE <span style="color: #339933;">|</span> PROCESS_VM_OPERATION <span style="color: #339933;">|</span> PROCESS_QUERY_INFORMATION<span style="color: #339933;">;</span>
    <span style="color: #339933;">*</span>hnd <span style="color: #339933;">=</span> OpenProcess<span style="color: #009900;">&#40;</span>perm<span style="color: #339933;">,</span> FALSE<span style="color: #339933;">,</span> prcs<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>hnd <span style="color: #339933;">==</span> NULL<span style="color: #009900;">&#41;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
&nbsp;
    snapshot <span style="color: #339933;">=</span> CreateToolhelp32Snapshot<span style="color: #009900;">&#40;</span>TH32CS_SNAPMODULE<span style="color: #339933;">,</span> prcs<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>snapshot <span style="color: #339933;">==</span> INVALID_HANDLE_VALUE<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    me.<span style="color: #202020;">dwSize</span> <span style="color: #339933;">=</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span>MODULEENTRY32<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>Module32First<span style="color: #009900;">&#40;</span>snapshot<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>me<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #b1b100;">do</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>_stricmp<span style="color: #009900;">&#40;</span>name<span style="color: #339933;">,</span> me.<span style="color: #202020;">szModule</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #339933;">*</span>baseAddress <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>DWORD <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>me.<span style="color: #202020;">modBaseAddr</span><span style="color: #339933;">;</span>
            <span style="color: #339933;">*</span>baseSize <span style="color: #339933;">=</span> me.<span style="color: #202020;">modBaseSize</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>Module32Next<span style="color: #009900;">&#40;</span>snapshot<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>me<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> argc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">**</span>argv<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> bombs<span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> width<span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> height<span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> offset<span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> ret<span style="color: #339933;">;</span>
    DWORD oldProtect<span style="color: #339933;">;</span>
    DWORD <span style="color: #339933;">*</span>baseAddress<span style="color: #339933;">;</span>
    DWORD baseSize<span style="color: #339933;">;</span>
    HANDLE snapshot<span style="color: #339933;">;</span>
    HANDLE hnd<span style="color: #339933;">;</span>
    PROCESSENTRY32 pe<span style="color: #339933;">;</span>
    SIZE_T bytesRead<span style="color: #339933;">;</span>
    SIZE_T bytesWritten<span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span><span style="color: #339933;">*</span> memory<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>argc <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Use: %s &lt;executable.exe&gt;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> argv<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Take snapshot of all processes</span>
    snapshot <span style="color: #339933;">=</span> CreateToolhelp32Snapshot<span style="color: #009900;">&#40;</span>TH32CS_SNAPPROCESS<span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>snapshot <span style="color: #339933;">==</span> INVALID_HANDLE_VALUE<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Error creating snapshot<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    pe.<span style="color: #202020;">dwSize</span> <span style="color: #339933;">=</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span>PROCESSENTRY32<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>Process32First<span style="color: #009900;">&#40;</span>snapshot<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>pe<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Error obtaining first process from the list<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    memory <span style="color: #339933;">=</span> NULL<span style="color: #339933;">;</span>
    <span style="color: #b1b100;">do</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>_stricmp<span style="color: #009900;">&#40;</span>pe.<span style="color: #202020;">szExeFile</span><span style="color: #339933;">,</span> argv<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>findModule<span style="color: #009900;">&#40;</span>argv<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> pe.<span style="color: #202020;">th32ProcessID</span><span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>hnd<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>baseAddress<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>baseSize<span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
            <span style="color: #009900;">&#123;</span>
                memory <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>malloc<span style="color: #009900;">&#40;</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span>baseSize<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>ReadProcessMemory<span style="color: #009900;">&#40;</span>hnd<span style="color: #339933;">,</span> baseAddress<span style="color: #339933;">,</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>memory<span style="color: #339933;">,</span> baseSize<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>bytesRead<span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
                <span style="color: #009900;">&#123;</span>
                    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Error reading process memory<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span>
                <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>Process32Next<span style="color: #009900;">&#40;</span>snapshot<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>pe<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>memory <span style="color: #339933;">!=</span> NULL<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> bytesRead<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #666666; font-style: italic;">// As the minimum board size is 9x9, we always have at least 11 bytes 0x10</span>
            <span style="color: #666666; font-style: italic;">// around the board, so we look for this row of bytes to find where the</span>
            <span style="color: #666666; font-style: italic;">// board starts</span>
            <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>memcmp<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>memory<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;<span style="color: #660099; font-weight: bold;">\x10</span><span style="color: #660099; font-weight: bold;">\x10</span><span style="color: #660099; font-weight: bold;">\x10</span><span style="color: #660099; font-weight: bold;">\x10</span><span style="color: #660099; font-weight: bold;">\x10</span><span style="color: #660099; font-weight: bold;">\x10</span><span style="color: #660099; font-weight: bold;">\x10</span><span style="color: #660099; font-weight: bold;">\x10</span><span style="color: #660099; font-weight: bold;">\x10</span><span style="color: #660099; font-weight: bold;">\x10</span><span style="color: #660099; font-weight: bold;">\x10</span>&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">11</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
            <span style="color: #009900;">&#123;</span>
                offset <span style="color: #339933;">=</span> i<span style="color: #339933;">;</span>
                bombs  <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span>memory<span style="color: #009900;">&#91;</span>i<span style="color: #339933;">-</span><span style="color: #0000dd;">16</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
                height <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span>memory<span style="color: #009900;">&#91;</span>i<span style="color: #339933;">-</span><span style="color: #0000dd;">12</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
                width  <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span>memory<span style="color: #009900;">&#91;</span>i<span style="color: #339933;">-</span><span style="color: #0000dd;">8</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
                <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;bombs  = %d<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> bombs<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;height = %d<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> width<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;width  = %d<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> height<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">// We found the board, now let's find the bombs (0x8F) and flag them</span>
        <span style="color: #666666; font-style: italic;">// Each line is 32 bytes long + 2 margin lines</span>
        <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #009900;">&#40;</span><span style="color: #0000dd;">32</span><span style="color: #339933;">*</span><span style="color: #009900;">&#40;</span>height<span style="color: #339933;">+</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> 
        <span style="color: #009900;">&#123;</span>
            <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>memory<span style="color: #009900;">&#91;</span>offset<span style="color: #339933;">+</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">==</span> <span style="color: #208080;">0x8F</span><span style="color: #009900;">&#41;</span>
                memory<span style="color: #009900;">&#91;</span>offset<span style="color: #339933;">+</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #208080;">0x0E</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">// Even thou we opened the process ReadWrite, we still need to change</span>
        <span style="color: #666666; font-style: italic;">// its protection settings.</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>VirtualProtectEx<span style="color: #009900;">&#40;</span>hnd<span style="color: #339933;">,</span> baseAddress<span style="color: #339933;">,</span> bytesRead<span style="color: #339933;">,</span> PAGE_READWRITE<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>oldProtect<span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Can't change process permission<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">// Write the whole process memory now!</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>WriteProcessMemory<span style="color: #009900;">&#40;</span>hnd<span style="color: #339933;">,</span> baseAddress<span style="color: #339933;">,</span> memory<span style="color: #339933;">,</span> bytesRead<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>bytesWritten<span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Can't write process memory<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Memory changed sucessfully. Minimize and maximize the game window!<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    getchar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>And the result is:</p>
<p>Before:<br />
<image src="/wp-content/uploads/2011/03/before.png"></img><br />
<br />
After:<br />
<image src="/wp-content/uploads/2011/03/after.png"></img></p>
<p>References:</p>
<p>MSDN - <a href="http://msdn.microsoft.com/en-us/library/ms682629%28v=vs.85%29.aspx" tagert="_blank">EnumProcesses Function</a><br />
MSDN - <a href="http://msdn.microsoft.com/en-us/library/ms682631%28VS.85%29.aspx" target="_blank">EnumProcessModules Function</a><br />
MSDN - <a href="http://msdn.microsoft.com/en-us/library/ms683196%28VS.85%29.aspx" target="_blank">GetModuleBaseName Function</a><br />
MSDN - <a href="http://msdn.microsoft.com/en-us/library/ms682623%28v=VS.85%29.aspx" target="_blank">Enumerating all processes example</a><br />
MSDN - <a href="http://msdn.microsoft.com/en-us/library/ms686701%28v=vs.85%29.aspx" target="_blank">Taking a Snapshot and Viewing Processes</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.gilgalab.com.br/2011/03/26/cheating-on-windows-minesweeper/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Conjunto de Mandelbrot</title>
		<link>http://www.gilgalab.com.br/2011/01/26/conjunto-de-mandelbrot/</link>
		<comments>http://www.gilgalab.com.br/2011/01/26/conjunto-de-mandelbrot/#comments</comments>
		<pubDate>Wed, 26 Jan 2011 21:51:29 +0000</pubDate>
		<dc:creator>Henrique</dc:creator>
				<category><![CDATA[C]]></category>
		<category><![CDATA[Matemática]]></category>
		<category><![CDATA[SDL]]></category>

		<guid isPermaLink="false">http://www.gilgalab.com.br/?p=105</guid>
		<description><![CDATA[Aprendi sobre fractais quando era um pouco mais novo e conheci o conjunto de Mandelbrot naquela época. Algum tempo atrás quis plotar o conjunto, porém não conseguia encontrar informações completas e/ou sequenciais que explicassem bem o assunto de uma maneira simples de entender. Sempre havia alguma coisa faltando. Escrevi esse texto com o intuito de [...]]]></description>
			<content:encoded><![CDATA[<p>Aprendi sobre fractais quando era um pouco mais novo e conheci o conjunto de Mandelbrot naquela época.<br />
Algum tempo atrás quis plotar o conjunto, porém não conseguia encontrar informações completas e/ou sequenciais que explicassem bem o assunto de uma maneira simples de entender. Sempre havia alguma coisa faltando.<br />
Escrevi esse texto com o intuito de fornecer um raciocínio lógico de se seguir para entender como o conjunto de Mandelbrot é formado e como plota-lo.<br />
Para aqueles que desejam conhecer mais sobre o conjunto, recomendo uma leitura no artigo da wikipedia sobre o assunto: <a href="http://pt.wikipedia.org/wiki/Conjunto_de_Mandelbrot" target="_blank">Conjunto de Mandelbrot</a><br />
O código que será apresentado mais afrente é escrito em linguagem C e utiliza a lib <a href="http://www.libsdl.org/" target="_blank">SDL</a>.</p>
<h3>Números Complexos</h3>
<p>Uma pequena introdução (mais uma revisão na verdade) do que é um número complexo.<br />
O número complexo é aquele que não pode ser representado no plano cartesiano real e é dividido em duas partes:<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=z%20%3D%20x%20%2B%20yi&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='z = x + yi' title='z = x + yi' class='latex' /><br />
</p>
<p><b>x</b> -> eixo X (Real)<br />
<b>y</b> -> eixo Y (Imaginário)<br />
<b>i</b> -> Número imaginário<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=i%20%3D%20%20%5Csqrt%7B-1%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='i =  \sqrt{-1}' title='i =  \sqrt{-1}' class='latex' /><br />
</br><br />
Sua representação é feita no plano complexo (também conhecido por plano de Argand):</p>
<p><a href="http://en.wikipedia.org/wiki/File:Complex_conjugate_picture.svg" target="_blank"><img src="http://www.gilgalab.com.br/wp-content/uploads/2011/01/plano_complexo.png" alt="Plano Complexo" title="Plano Complexo" width="200" height="263" class="aligncenter size-full wp-image-111" /></a></p>
<p>Logo, quando se deseja plotar um número complexo utiliza-se a parte real como valor a ser marcado no eixo X, e a parte imaginária para ser marcada no eixo Y, representando assim um ponto no plano.</p>
<p><b>PS:</b> Há muito mais sobre os números complexos do que apenas isso. Para conhecer mais afundo e entender melhor sobre o conjunto de mandelbrot, é bastante interessante estudar os números complexos... pode ser uma boa hora para desenterrar aqueles seus livros de matemática do ensino fundamental/médio.</p>
<h3>O conjunto de Mandelbrot</h3>
<p>O conjunto de Mandelbrot é definido pela seguinte equação:<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=z_%7Bn%2B1%7D%20%3D%20%28z_n%29%5E2%20%2B%20c&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='z_{n+1} = (z_n)^2 + c' title='z_{n+1} = (z_n)^2 + c' class='latex' /><br />
<br />
Onde 'z' e 'c' são números imaginários do formato:<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=z%20%3D%20u%20%2B%20wi&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='z = u + wi' title='z = u + wi' class='latex' /><br />
<br />
<b>u</b> -> Parte Real (Coordenada do eixo X)<br />
<b>w</b> -> Parte Imaginária (Coordenada do eixo Y)<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=c%20%3D%20a%20%2B%20bi&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c = a + bi' title='c = a + bi' class='latex' /><br />
<br />
<b>a</b> -> Parte Real (Coordenada do eixo X)<br />
<b>b</b> -> Parte Imaginária (Coordenada do eixo Y)</p>
<p>Como pode-se perceber pela equação, esse conjunto é definido através de uma fórmula recursiva, onde o resultado atual depende do resultado anterior (esse comportamento é observado também na série de Fibonacci).<br />
A equação por si só não é suficiente para definir o conjunto. Pontos cuja distância da origem tenham valor maior que 2, não fazem parte do conjunto (Pode-se perceber (e provar) que quando um ponto atinge uma distância maior que 2, nas iterações que se seguem farão com que ele cresça rumo ao infinito).<br />
Para os que não se lembram, a seguinte fórmula calcula a distância entre dois pontos:<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=d%20%3D%20%5Csqrt%7B%28x_1%20-%20x_0%29%5E2%20%2B%20%28y_1%20-%20y_0%29%5E2%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='d = \sqrt{(x_1 - x_0)^2 + (y_1 - y_0)^2}' title='d = \sqrt{(x_1 - x_0)^2 + (y_1 - y_0)^2}' class='latex' /><br />
<br />
Considerando a origem do plano no ponto O(0,0), a fórmula fica da seguinte maneira:<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=%20%20d%20%3D%20%5Csqrt%7B%28x_1%20-%200%29%5E2%20%2B%20%28y_1%20-%200%29%5E2%7D%5C%5C%20%20d%20%3D%20%5Csqrt%7Bx_1%5E2%20%2B%20y_1%5E2%7D%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='  d = \sqrt{(x_1 - 0)^2 + (y_1 - 0)^2}\\  d = \sqrt{x_1^2 + y_1^2}  ' title='  d = \sqrt{(x_1 - 0)^2 + (y_1 - 0)^2}\\  d = \sqrt{x_1^2 + y_1^2}  ' class='latex' /><br />
<br />
De volta a equação que define a presença dos elementos do conjunto a expanão da recursividade da fórmula fica da seguinte maneira:<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=%20%20Z_0%20%3D%200%20%2B%200i%20%20%20%20%3D%3E%20Z_0%20%3D%200%5C%5C%20%20Z_1%20%3D%20Z_0%5E2%20%2B%20c%20%3D%3E%20Z_1%20%3D%20c%5C%5C%20%20Z_2%20%3D%20Z_1%5E2%20%2B%20c%20%3D%3E%20Z_2%20%3D%20c%5E2%20%2B%20c%5C%5C%20%20Z_3%20%3D%20Z_2%5E2%20%2B%20c%20%3D%3E%20Z_3%20%3D%20%28c%5E2%20%2B%20c%29%5E2%20%2B%20c%5C%5C%20%20...%5C%5C%20%20Z_n%2B1%20%3D%20%28Z_n%29%5E2%20%2B%20c%5C%5C%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='  Z_0 = 0 + 0i    =&gt; Z_0 = 0\\  Z_1 = Z_0^2 + c =&gt; Z_1 = c\\  Z_2 = Z_1^2 + c =&gt; Z_2 = c^2 + c\\  Z_3 = Z_2^2 + c =&gt; Z_3 = (c^2 + c)^2 + c\\  ...\\  Z_n+1 = (Z_n)^2 + c\\  ' title='  Z_0 = 0 + 0i    =&gt; Z_0 = 0\\  Z_1 = Z_0^2 + c =&gt; Z_1 = c\\  Z_2 = Z_1^2 + c =&gt; Z_2 = c^2 + c\\  Z_3 = Z_2^2 + c =&gt; Z_3 = (c^2 + c)^2 + c\\  ...\\  Z_n+1 = (Z_n)^2 + c\\  ' class='latex' /><br />
<br />
Vamos voltar um pouco a teoria de números complexos então e fazer uma análise mais a fundo da equação que define o conjunto de Mandelbrot, para que possa ser aplicada em nosso algoritmo:<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=%20%20z%5E2%20%3D%20%28u%20%2B%20wi%29%5E2%5C%5C%20%20z%5E2%20%3D%20u%5E2%20%2B%202%2Au%2Awi%20%2B%20wi%5E2%5C%5C%20%20z%5E2%20%3D%20u%5E2%20%2B%202%2Au%2Awi%20%2B%20%28w%5E2%20%2A%20i%5E2%29%5C%5C%20%20z%5E2%20%3D%20u%5E2%20%2B%202%2Au%2Awi%20%2B%20%28w%5E2%20%2A%20-1%29%5C%5C%20%20z%5E2%20%3D%20u%5E2%20%2B%202%2Au%2Awi%20-%20w%5E2%5C%5C%20%20z%5E2%20%3D%20u%5E2%20-%20w%5E2%20%2B%202%2Au%2Awi%5C%5C%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='  z^2 = (u + wi)^2\\  z^2 = u^2 + 2*u*wi + wi^2\\  z^2 = u^2 + 2*u*wi + (w^2 * i^2)\\  z^2 = u^2 + 2*u*wi + (w^2 * -1)\\  z^2 = u^2 + 2*u*wi - w^2\\  z^2 = u^2 - w^2 + 2*u*wi\\  ' title='  z^2 = (u + wi)^2\\  z^2 = u^2 + 2*u*wi + wi^2\\  z^2 = u^2 + 2*u*wi + (w^2 * i^2)\\  z^2 = u^2 + 2*u*wi + (w^2 * -1)\\  z^2 = u^2 + 2*u*wi - w^2\\  z^2 = u^2 - w^2 + 2*u*wi\\  ' class='latex' /><br />
<br />
A parte real do número que representa o eixo X, é dado pela seguinte parte da equação:<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=u%5E2%20-%20w%5E2&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='u^2 - w^2' title='u^2 - w^2' class='latex' /><br />
<br />
A parte imaginária do número que representa o eixo Y, é dado pela seguinte parte da equação:<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=2%2Au%2Awi&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='2*u*wi' title='2*u*wi' class='latex' /><br />
<br />
Portanto:<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=%20%20%09z_%7Bn%2B1%7D%20%3D%20%28z_n%29%5E2%20%2B%20c%5C%5C%20%20%09z_%7Bn%2B1%7D%20%3D%20%28u_n%5E2%20-%20w_n%5E2%20%2B%202%2Au_n%2Aw_n%2Ai%29%20%2B%20%28a%20%2B%20bi%29%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='  	z_{n+1} = (z_n)^2 + c\\  	z_{n+1} = (u_n^2 - w_n^2 + 2*u_n*w_n*i) + (a + bi)  ' title='  	z_{n+1} = (z_n)^2 + c\\  	z_{n+1} = (u_n^2 - w_n^2 + 2*u_n*w_n*i) + (a + bi)  ' class='latex' /><br />
</p>
<p>Em termos de código seria algo parecido com:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">void</span> mandelbrot<span style="color: #009900;">&#40;</span><span style="color: #993333;">float</span> u<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> w<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> a<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> b<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	eixoX <span style="color: #339933;">=</span> u<span style="color: #339933;">^</span><span style="color: #0000dd;">2</span> <span style="color: #339933;">-</span> w<span style="color: #339933;">^</span><span style="color: #0000dd;">2</span> <span style="color: #339933;">+</span> a<span style="color: #339933;">;</span>
	eixoY <span style="color: #339933;">=</span> <span style="color: #0000dd;">2</span> <span style="color: #339933;">*</span> u <span style="color: #339933;">*</span> w <span style="color: #339933;">+</span> b<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Vamos supor alguns valores para as variáveis envolvidas, apenas para fim de demonstrar como ficaria a conta:<br />
<i>a = 2</i><br />
<i>b = 3</i><br />
<i>u = 5</i><br />
<i>w = 1</i><br />
Substituindo na equação:<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=%20%20%09z_%7Bn%2B1%7D%20%3D%20%285%5E2%20-%201%5E2%20%2B%202%2A5%2A1%2Ai%29%20%2B%20%282%20%2B%203i%29%5C%5C%20%20%09z_%7Bn%2B1%7D%20%3D%20%2825%20-%201%20%2B%2010i%29%20%2B%202%20%2B%203i%5C%5C%20%20%09z_%7Bn%2B1%7D%20%3D%2024%20%2B%2010i%20%2B%202%20%2B%203i%5C%5C%20%20%09z_%7Bn%2B1%7D%20%3D%2026%20%2B%2013i%5C%5C%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='  	z_{n+1} = (5^2 - 1^2 + 2*5*1*i) + (2 + 3i)\\  	z_{n+1} = (25 - 1 + 10i) + 2 + 3i\\  	z_{n+1} = 24 + 10i + 2 + 3i\\  	z_{n+1} = 26 + 13i\\  ' title='  	z_{n+1} = (5^2 - 1^2 + 2*5*1*i) + (2 + 3i)\\  	z_{n+1} = (25 - 1 + 10i) + 2 + 3i\\  	z_{n+1} = 24 + 10i + 2 + 3i\\  	z_{n+1} = 26 + 13i\\  ' class='latex' /><br />
<br />
Logo temos o ponto (26,13) no plano imaginário.</p>
<p>É claro que os valores dados acima são apenas um exemplo para demonstrar como é feito o calculo da equação e não se encontram no conjunto de Mandelbrot.</p>
<p>Eis então uma breve explicação de como funcionará o algoritmo para determinar se um número faz ou não parte do conjunto:</p>
<ul>
<li>A primeira iteração tem valor 0 para 'z' e 'c' receberá o valor do ponto que desejamos testar.
<li>Executa-se recursivamente o cálculo até um limite definido pelo programador
<li>A recursão ocorre para cada ponto que desejamos testar para verificar se está ou não contido no conjunto de Mandelbrot.
<li>O conjunto de pontos que podemos testar é infinito e os valores de x devem estar no intervalo [-2; 1] e os valores de y estejam no intervalo [-1; 1]. Não se esqueça, entre dois pontos existem infinitos números quando consideramos o conjunto dos números complexos.
</ul>
<p>Vamos trabalhar com um exemplo!<br />
Suponha que desejamos testar se o ponto ((0,3), (0,4)) faz parte do conjunto. Teremos então:<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=%20%20c%20%3D%200%2C3%20%2B%200%2C4i%5C%5C%20%20z_%7Bn0%7D%20%3D%200%20%2B%200%2C3%20%2B%200%2C4i%5C%5C%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='  c = 0,3 + 0,4i\\  z_{n0} = 0 + 0,3 + 0,4i\\  ' title='  c = 0,3 + 0,4i\\  z_{n0} = 0 + 0,3 + 0,4i\\  ' class='latex' /><br />
<br />
Tem-se o ponto ((0,3), (0,4)). É necessário calcular a distância desse ponto à origem.<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=%20%20d%20%3D%20%5Csqrt%7B0%2C3%5E2%20%2B%200%2C4%5E2%7D%5C%5C%20%20d%20%3D%200.5%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='  d = \sqrt{0,3^2 + 0,4^2}\\  d = 0.5  ' title='  d = \sqrt{0,3^2 + 0,4^2}\\  d = 0.5  ' class='latex' /><br />
<br />
A distância é menor que 2, logo deve-se realizar o cálculo da próxima iteração<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=%20%20z_%7Bn1%7D%20%3D%20z_%7Bn0%7D%5E2%20%2B%20c%5C%5C%20%20z_%7Bn1%7D%20%3D%20%280%2C3%20%2B%200%2C4i%29%5E2%20%2B%20%280%2C3%20%2B%200%2C4i%29%5C%5C%20%20z_%7Bn1%7D%20%3D%20%280%2C3%5E2%20%2B%202%2A0%2C3%2A0%2C4i%20%2B%200%2C4i%5E2%29%20%2B%20%280%2C3%20%2B%200%2C4i%29%5C%5C%20%20z_%7Bn1%7D%20%3D%20%280%2C09%20%2B%200%2C24i%20-%200%2C16i%29%20%2B%20%280%2C3%20%2B%200%2C4i%29%5C%5C%20%20z_%7Bn1%7D%20%3D%200%2C09%20%2B%200%2C24i%20-%200%2C16i%20%2B%200%2C3%20%2B%200%2C4i%5C%5C%20%20z_%7Bn1%7D%20%3D%200%2C39%20%2B%200%2C48i%5C%5C%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='  z_{n1} = z_{n0}^2 + c\\  z_{n1} = (0,3 + 0,4i)^2 + (0,3 + 0,4i)\\  z_{n1} = (0,3^2 + 2*0,3*0,4i + 0,4i^2) + (0,3 + 0,4i)\\  z_{n1} = (0,09 + 0,24i - 0,16i) + (0,3 + 0,4i)\\  z_{n1} = 0,09 + 0,24i - 0,16i + 0,3 + 0,4i\\  z_{n1} = 0,39 + 0,48i\\  ' title='  z_{n1} = z_{n0}^2 + c\\  z_{n1} = (0,3 + 0,4i)^2 + (0,3 + 0,4i)\\  z_{n1} = (0,3^2 + 2*0,3*0,4i + 0,4i^2) + (0,3 + 0,4i)\\  z_{n1} = (0,09 + 0,24i - 0,16i) + (0,3 + 0,4i)\\  z_{n1} = 0,09 + 0,24i - 0,16i + 0,3 + 0,4i\\  z_{n1} = 0,39 + 0,48i\\  ' class='latex' /><br />
<br />
Tem-se o ponto ((0,39), (0,48)). É necessário calcular a distância desse ponto à origem.<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=%20%20d%20%3D%20%5Csqrt%7B0%2C39%5E2%20%2B%200%2C48%5E2%7D%5C%5C%20%20d%20%3D%200.6184667%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='  d = \sqrt{0,39^2 + 0,48^2}\\  d = 0.6184667  ' title='  d = \sqrt{0,39^2 + 0,48^2}\\  d = 0.6184667  ' class='latex' /><br />
<br />
Novamente a distância é menor que 2, logo deve-se realizar o cálculo da próxima iteração.<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=%20%20z_%7Bn2%7D%20%3D%20z_%7Bn1%7D%5E2%20%2B%20c%5C%5C%20%20z_%7Bn2%7D%20%3D%20%280%2C39%20%2B%200%2C48i%29%5E2%20%2B%20%280%2C3%20%2B%200%2C4i%29%5C%5C%20%20...%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='  z_{n2} = z_{n1}^2 + c\\  z_{n2} = (0,39 + 0,48i)^2 + (0,3 + 0,4i)\\  ...  ' title='  z_{n2} = z_{n1}^2 + c\\  z_{n2} = (0,39 + 0,48i)^2 + (0,3 + 0,4i)\\  ...  ' class='latex' /> </p>
<p>Esse processo se repetirá por n iterações. No caso do código abaixo, isso se repetirá 1024 vezes ou até que a distância do ponto à origem seja maior que 2.<br />
Caso as 1024 iterações ocorram sem que o resultado de nenhuma delas extrapole a distância de 2 da origem, então marcamos o ponto 'c' como fazendo parte do conjunto.<br />
Por exemplo, quando iteramos o ponto p(-0.75, -0.01562) ao chegarmos na iteração 201, o valor estoura para fora do limite permitido pelo conjunto, atingindo o ponto q(1.11917, 3.12583) que está a uma distância maior do que 2 da origem. Logo, o ponto p(-0.75, -0.01562) não está no conjunto de Mandelbrot.</p>
<h3>Implementando</h3>
<p>A seguir então uma implementação do algoritmo para plotar o gráfico referente ao conjunto de Mandelbrot.<br />
O código está escrito em C e utiliza a lib SDL para os gráficos.<br />
Boa parte do código está comentada e acredito que sejam suficientes para explicar seu funcionamento.<br />
O código não está otimizado, então ele demora um pouco a executar (no meu computador leva coisa de 5 segundos, sendo que o processador é um Core 2 Duo E7400 de 2.8ghz).<br />
Sinta-se a vontade para otimiza-lo e adicionar cor ao gráfico.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">&nbsp;
<span style="color: #808080; font-style: italic;">/**
 * Salve o código em um arquivo chamado mandelbrot.c
 * Compile com: gcc -Wall -lm -lSDL -o mandelbrot mandelbrot.c
 * Execute com: ./mandelbrot
 * Use o código e altere a vontade. Se precisar de alguma ajuda
 * ou tiver alguma duvida, fique a vontade para me contactar.
 * Se for republicar o código em algum lugar, agradeço se mantiver
 * os créditos ou um link para o código original.
 *
 * Autor: Henrique M. D.
 * Email: typoon at gmail dot com
 */</span>
&nbsp;
<span style="color: #339933;">#include &lt;stdio.h&gt;</span>
<span style="color: #339933;">#include &lt;math.h&gt;</span>
<span style="color: #339933;">#include &lt;SDL/SDL.h&gt;</span>
&nbsp;
<span style="color: #339933;">#define WIDTH  800 /* Largura da tela */</span>
<span style="color: #339933;">#define HEIGHT 800 /* Altura da tela */</span>
<span style="color: #339933;">#define MAX_ITER 1024</span>
&nbsp;
<span style="color: #993333;">void</span> setPixel<span style="color: #009900;">&#40;</span>SDL_Surface <span style="color: #339933;">*</span>screen<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> x<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> y<span style="color: #339933;">,</span> SDL_Color <span style="color: #339933;">*</span>cor<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">void</span> scaleXY<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> pX<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> pY<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> <span style="color: #339933;">*</span>cX<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> <span style="color: #339933;">*</span>cY<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> mandelbrot<span style="color: #009900;">&#40;</span><span style="color: #993333;">float</span> zX<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> zY<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> cX<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> cY<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> iter<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">float</span> distOrigem<span style="color: #009900;">&#40;</span><span style="color: #993333;">float</span> x<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> y<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">void</span> putpixel<span style="color: #009900;">&#40;</span>SDL_Surface <span style="color: #339933;">*</span>surface<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> x<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> y<span style="color: #339933;">,</span> Uint32 pixel<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> argc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">**</span>argv<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #993333;">int</span> i<span style="color: #339933;">,</span> j<span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> iter<span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> exit<span style="color: #339933;">;</span>
    <span style="color: #993333;">float</span> cX<span style="color: #339933;">,</span> cY<span style="color: #339933;">;</span>
&nbsp;
    SDL_Surface <span style="color: #339933;">*</span>screen<span style="color: #339933;">;</span>
    SDL_Color black<span style="color: #339933;">;</span>
    SDL_Color white<span style="color: #339933;">;</span>
    SDL_Event event<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>SDL_Init<span style="color: #009900;">&#40;</span>SDL_INIT_VIDEO<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Error initializing SDL [%s]<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> SDL_GetError<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    atexit<span style="color: #009900;">&#40;</span>SDL_Quit<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    screen <span style="color: #339933;">=</span> SDL_SetVideoMode<span style="color: #009900;">&#40;</span>WIDTH<span style="color: #339933;">,</span> HEIGHT<span style="color: #339933;">,</span> <span style="color: #0000dd;">32</span><span style="color: #339933;">,</span> SDL_HWSURFACE<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>screen <span style="color: #339933;">==</span> NULL<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Error setting video mode [%s]<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> SDL_GetError<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    black.<span style="color: #202020;">r</span> <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
    black.<span style="color: #202020;">g</span> <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
    black.<span style="color: #202020;">b</span> <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
    white.<span style="color: #202020;">r</span> <span style="color: #339933;">=</span> <span style="color: #0000dd;">255</span><span style="color: #339933;">;</span>
    white.<span style="color: #202020;">g</span> <span style="color: #339933;">=</span> <span style="color: #0000dd;">255</span><span style="color: #339933;">;</span>
    white.<span style="color: #202020;">b</span> <span style="color: #339933;">=</span> <span style="color: #0000dd;">255</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> WIDTH<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>j <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> j <span style="color: #339933;">&lt;</span> HEIGHT<span style="color: #339933;">;</span> j<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            scaleXY<span style="color: #009900;">&#40;</span>i<span style="color: #339933;">,</span> j<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>cX<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>cY<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #808080; font-style: italic;">/* Converter o pixel em coordenadas */</span>
            iter <span style="color: #339933;">=</span> mandelbrot<span style="color: #009900;">&#40;</span><span style="color:#800080;">0.0</span><span style="color: #339933;">,</span> <span style="color:#800080;">0.0</span><span style="color: #339933;">,</span> cX<span style="color: #339933;">,</span> cY<span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>iter <span style="color: #339933;">==</span> MAX_ITER<span style="color: #009900;">&#41;</span> <span style="color: #808080; font-style: italic;">/* ponto do conjunto, pintar de preto */</span>
            <span style="color: #009900;">&#123;</span>
                setPixel<span style="color: #009900;">&#40;</span>screen<span style="color: #339933;">,</span> i<span style="color: #339933;">,</span> j<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>black<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
            <span style="color: #b1b100;">else</span>
            <span style="color: #009900;">&#123;</span>
                setPixel<span style="color: #009900;">&#40;</span>screen<span style="color: #339933;">,</span> i<span style="color: #339933;">,</span> j<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>white<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    SDL_Flip<span style="color: #009900;">&#40;</span>screen<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    exit <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>exit<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        SDL_PollEvent<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>event<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">switch</span><span style="color: #009900;">&#40;</span>event.<span style="color: #202020;">type</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #b1b100;">case</span> SDL_QUIT<span style="color: #339933;">:</span>
                exit <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">/**
 * Função praticamente copiada de:
 * http://www.cpp-home.com/tutorials/154_1.htm
 * Com leves alterações
 * Serve para setar o pixel na superficie com a cor especificada
 *
 * @param screen Superficie onde pintar o pixel
 * @param x Posicao x do pixel
 * @param y Posicao y do pixel
 * @param cor A cor que se deseja pintar o pixel
 *
 */</span>
<span style="color: #993333;">void</span> setPixel<span style="color: #009900;">&#40;</span>SDL_Surface <span style="color: #339933;">*</span>screen<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> x<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> y<span style="color: #339933;">,</span> SDL_Color <span style="color: #339933;">*</span>cor<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">int</span> bpp<span style="color: #339933;">;</span>
    Uint8 <span style="color: #339933;">*</span>p<span style="color: #339933;">;</span>
    Uint32 pixel<span style="color: #339933;">;</span>
&nbsp;
    pixel <span style="color: #339933;">=</span> SDL_MapRGB<span style="color: #009900;">&#40;</span>screen<span style="color: #339933;">-&gt;</span>format<span style="color: #339933;">,</span> cor<span style="color: #339933;">-&gt;</span>r<span style="color: #339933;">,</span> cor<span style="color: #339933;">-&gt;</span>g<span style="color: #339933;">,</span> cor<span style="color: #339933;">-&gt;</span>b<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    bpp <span style="color: #339933;">=</span> screen<span style="color: #339933;">-&gt;</span>format<span style="color: #339933;">-&gt;</span>BytesPerPixel<span style="color: #339933;">;</span>
    p <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Uint8 <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>screen<span style="color: #339933;">-&gt;</span>pixels <span style="color: #339933;">+</span> y <span style="color: #339933;">*</span> screen<span style="color: #339933;">-&gt;</span>pitch <span style="color: #339933;">+</span> x <span style="color: #339933;">*</span> bpp<span style="color: #339933;">;</span>
&nbsp;
    SDL_LockSurface<span style="color: #009900;">&#40;</span>screen<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">switch</span><span style="color: #009900;">&#40;</span>bpp<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">case</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">:</span>
            <span style="color: #339933;">*</span>p <span style="color: #339933;">=</span> pixel<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #b1b100;">case</span> <span style="color: #0000dd;">2</span><span style="color: #339933;">:</span>
            <span style="color: #339933;">*</span><span style="color: #009900;">&#40;</span>Uint16 <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>p <span style="color: #339933;">=</span> pixel<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #b1b100;">case</span> <span style="color: #0000dd;">3</span><span style="color: #339933;">:</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>SDL_BYTEORDER <span style="color: #339933;">==</span> SDL_BIG_ENDIAN<span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            p<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>pixel <span style="color: #339933;">&gt;&gt;</span> <span style="color: #0000dd;">16</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span> <span style="color: #208080;">0xff</span><span style="color: #339933;">;</span>
            p<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>pixel <span style="color: #339933;">&gt;&gt;</span> <span style="color: #0000dd;">8</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span> <span style="color: #208080;">0xff</span><span style="color: #339933;">;</span>
            p<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> pixel <span style="color: #339933;">&amp;</span> <span style="color: #208080;">0xff</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
            p<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> pixel <span style="color: #339933;">&amp;</span> <span style="color: #208080;">0xff</span><span style="color: #339933;">;</span>
            p<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>pixel <span style="color: #339933;">&gt;&gt;</span> <span style="color: #0000dd;">8</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span> <span style="color: #208080;">0xff</span><span style="color: #339933;">;</span>
            p<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>pixel <span style="color: #339933;">&gt;&gt;</span> <span style="color: #0000dd;">16</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span> <span style="color: #208080;">0xff</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #b1b100;">case</span> <span style="color: #0000dd;">4</span><span style="color: #339933;">:</span>
            <span style="color: #339933;">*</span><span style="color: #009900;">&#40;</span>Uint32 <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>p <span style="color: #339933;">=</span> pixel<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    SDL_UnlockSurface<span style="color: #009900;">&#40;</span>screen<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
<span style="color: #808080; font-style: italic;">/**
 * Faz a escala que converte o valor do pixel da tela
 * para o equivalente do plano complexo para o conjunto de Mandelbrot
 * que encontra-se em:
 * x = [-2, 1]
 * y = [-1, 1]
 *
 * @param pX - Pixel no eixo X
 * @param pY - Pixel no eixo Y
 * @param cX - Valor em que o pixel é representado no plano complexo entre -2 e 1
 * @param cY - Valor em que o pixel é representado no plano complexo entre -1 e 1
 *
 */</span> 
<span style="color: #993333;">void</span> scaleXY<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> pX<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> pY<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> <span style="color: #339933;">*</span>cX<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> <span style="color: #339933;">*</span>cY<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #993333;">int</span> coordX0<span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> coordY0<span style="color: #339933;">;</span>
    <span style="color: #993333;">float</span> scaleX<span style="color: #339933;">;</span>
    <span style="color: #993333;">float</span> scaleY<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">/* 2.5 para esquerda do eixo */</span>
    <span style="color: #808080; font-style: italic;">/* 1.0 para direita do eixo */</span>
    coordX0 <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>WIDTH <span style="color: #339933;">/</span> <span style="color:#800080;">3.0</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> <span style="color:#800080;">2.0</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">/* 1.0 para cima do eixo  */</span>
    <span style="color: #808080; font-style: italic;">/* 1.0 para baixo do eixo */</span>
    coordY0 <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>HEIGHT <span style="color: #339933;">/</span> <span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
&nbsp;
    scaleX <span style="color: #339933;">=</span> <span style="color:#800080;">3.0</span> <span style="color: #339933;">/</span> WIDTH<span style="color: #339933;">;</span>
    scaleY <span style="color: #339933;">=</span> <span style="color:#800080;">2.0</span> <span style="color: #339933;">/</span> HEIGHT<span style="color: #339933;">;</span>
&nbsp;
&nbsp;
    <span style="color: #339933;">*</span>cX <span style="color: #339933;">=</span> <span style="color: #339933;">-</span><span style="color:#800080;">2.0</span> <span style="color: #339933;">+</span> <span style="color: #009900;">&#40;</span>pX <span style="color: #339933;">*</span> scaleX<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>pY <span style="color: #339933;">&gt;</span> coordY0<span style="color: #009900;">&#41;</span> <span style="color: #808080; font-style: italic;">/* Coordenada Y negativa */</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #339933;">*</span>cY <span style="color: #339933;">=</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span> <span style="color: #339933;">+</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>HEIGHT <span style="color: #339933;">-</span> pY<span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> scaleY<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #b1b100;">else</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #339933;">*</span>cY <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>pY <span style="color: #339933;">-</span> <span style="color: #009900;">&#40;</span>HEIGHT<span style="color: #339933;">/</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> scaleY<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">/**
 * Essa função verifica se o ponto que lhe foi passado pertence
 * ao conjunto de Mandelbrot para MAX_ITER iteraçãoes.
 * Caso não pertença, ela retorna o valor da iteração na qual o ponto
 * extrapolou o range permitido do conjunto, caso contrário, o valor
 * retornado será igual a MAX_ITER
 *
 * @param zX - Valor do eixo real X para o numero complexo z
 * @param zY - Valor do eixo imaginario Y para o numero complexo z
 * @param cX - Valor do eixo real X para o numero complexo c
 * @param cY - Valor do eixo imaginário Y para o numero complexo c
 * @param iter - Número da iteração na qual estamos (É o valor de n em Z_n)
 * @return A quantidade de iterações recursivas que foram executadas
 *
 */</span>
<span style="color: #993333;">int</span> mandelbrot<span style="color: #009900;">&#40;</span><span style="color: #993333;">float</span> zX<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> zY<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> cX<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> cY<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> iter<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #993333;">float</span> dX<span style="color: #339933;">;</span>
    <span style="color: #993333;">float</span> dY<span style="color: #339933;">;</span>
&nbsp;
    dX <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>zX<span style="color: #339933;">*</span>zX<span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> <span style="color: #009900;">&#40;</span>zY<span style="color: #339933;">*</span>zY<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> cX<span style="color: #339933;">;</span>
    dY <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #0000dd;">2</span><span style="color: #339933;">*</span>zX<span style="color: #339933;">*</span>zY<span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> cY<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>iter <span style="color: #339933;">&gt;=</span> MAX_ITER<span style="color: #009900;">&#41;</span> <span style="color: #808080; font-style: italic;">/* Ponto passou por todas iterações e está no conjunto */</span>
        <span style="color: #b1b100;">return</span> iter<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>distOrigem<span style="color: #009900;">&#40;</span>dX<span style="color: #339933;">,</span> dY<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&lt;=</span> <span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span> <span style="color: #808080; font-style: italic;">/* Ponto está no conjunto */</span>
        <span style="color: #b1b100;">return</span> mandelbrot<span style="color: #009900;">&#40;</span>dX<span style="color: #339933;">,</span> dY<span style="color: #339933;">,</span> cX<span style="color: #339933;">,</span> cY<span style="color: #339933;">,</span> <span style="color: #339933;">++</span>iter<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> iter<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">/**
 * Calcula a distancia do ponto passado a origem O(0,0)
 * do plano
 *
 * @param x Valor de X do ponto
 * @param y Valor de Y do ponto
 * @return A distância do ponto a origem
 */</span>
<span style="color: #993333;">float</span> distOrigem<span style="color: #009900;">&#40;</span><span style="color: #993333;">float</span> x<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> y<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">return</span> sqrtf<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>x<span style="color: #339933;">*</span>x<span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #009900;">&#40;</span>y<span style="color: #339933;">*</span>y<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>O resultado desse programa é uma janela com a seguinte imagem<br />
<a href="http://www.gilgalab.com.br/wp-content/uploads/2011/01/mandelbrot.png"><img src="http://www.gilgalab.com.br/wp-content/uploads/2011/01/mandelbrot.png" alt="mandelbrot" title="mandelbrot" width="600" height="600" class="aligncenter size-medium wp-image-132" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.gilgalab.com.br/2011/01/26/conjunto-de-mandelbrot/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Project Euler &#8211; Problema 1</title>
		<link>http://www.gilgalab.com.br/2011/01/19/project-euler-problema-1/</link>
		<comments>http://www.gilgalab.com.br/2011/01/19/project-euler-problema-1/#comments</comments>
		<pubDate>Thu, 20 Jan 2011 00:24:48 +0000</pubDate>
		<dc:creator>Henrique</dc:creator>
				<category><![CDATA[C]]></category>
		<category><![CDATA[Matemática]]></category>
		<category><![CDATA[Project Euler]]></category>

		<guid isPermaLink="false">http://www.gilgalab.com.br/?p=83</guid>
		<description><![CDATA[Ao perguntar a um amigo no IRC sobre uma recomendação de hobby, ele me respondeu 'Matemática!'. Eu tinha em mente um hobby onde não precisasse pensar muito, mas matemática já havia me passado pela mente diversas vezes. Acabei por arranjar um hobby onde não é preciso pensar muito e resolvi também adicionar a matemática como [...]]]></description>
			<content:encoded><![CDATA[<p>Ao perguntar a um amigo no IRC sobre uma recomendação de hobby, ele me respondeu 'Matemática!'. Eu tinha em mente um hobby onde não precisasse pensar muito, mas matemática já havia me passado pela mente diversas vezes.<br />
Acabei por arranjar um hobby onde não é preciso pensar muito e resolvi também adicionar a matemática como um hobby. Esse post é para falar sobre este último :)<br />
Faz algum tempo fui apresentado ao <a href="http://www.projecteuler.net" target="_blank">'Project Euler'</a>, um site com desafios matemáticos que podem ser resolvidos com ou sem o auxílio de um computador. Decidi que vou tentar resolver os problemas, inicialmente sem o auxílio de um computador (quando possível), e então implementarei uma solução utilizando programação.</p>
<p><b> O Problema </b></p>
<blockquote><p>
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.<br />
Find the sum of all the multiples of 3 or 5 below 1000.
</p></blockquote>
<p><i>Em português:</i></p>
<blockquote><p>
Se nós listarmos todos os números naturais abaixo de 10 que sejam múltiplos de 3 ou 5, teremos 3, 5, 6 e 9. A soma desses múltiplos é 23.<br />
Encontre a soma de todos os multiplos de 3 ou 5 abaixo de 1000.
</p></blockquote>
<p><b>A Solução Matemática</b></p>
<p>A primeira idéia para resolver esse problema é dar uma olhada em parte dos conjuntos formados pelos números menores que 1000 e múltiplos de 3 e de 5<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=M3%20%3D%20%5C%7B3%2C%206%2C%209%2C%2012%2C%2015%2C%2018%2C%2021%2C%2024%2C%2027%2C%2030%2C%2033%2C%2036%2C%20...%2C%20996%2C%20999%5C%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='M3 = \{3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, ..., 996, 999\}' title='M3 = \{3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, ..., 996, 999\}' class='latex' /><br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=M5%20%3D%20%5C%7B5%2C%2010%2C%2015%2C%2020%2C%2025%2C%2030%2C%2035%2C%2040%2C%2045%2C%2050%2C%2055%2C%2060%2C%20...%2C%20990%2C%20995%5C%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='M5 = \{5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, ..., 990, 995\}' title='M5 = \{5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, ..., 990, 995\}' class='latex' /><br />
</p>
<p><i>M3 terá um total de 333 elementos (999 / 3)</i><br />
<i>M5 terá um total de 199 elementos (999 / 5)</i></p>
<p>Algo para se notar é que em ambos os conjuntos existem números repetidos, como por exemplo {15, 30, 45, 60, ...}, logo se realizarmos a soma dos dois conjuntos teremos duplicidade desses números nos dando a resposta incorreta.<br />
Para eliminar esses números de um dos dois conjuntos, precisamos simplesmente subtrair a soma de todos eles do resultado final e para isso precisamos descobrir quais são todos os números múltiplos de 3 <b>E</b> 5 e aplicar o mesmo procedimento de somatória.<br />
Como descobrir esses números então? Simples! Calcula-se o M.M.C. (mínimo múltiplo comum) de 3 e 5, e encontra-se o conjunto dos múltiplos desse valor encontrado para todos os valores abaixo de 1000.<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=MMC%283%2C5%29%20%3D%2015&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='MMC(3,5) = 15' title='MMC(3,5) = 15' class='latex' /><br />
</p>
<p>Temos então o novo conjunto M15:<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=M15%20%3D%20%5C%7B15%2C%2030%2C%2045%2C%2060%2C%2075%2C%2090%2C%20...%2C%20975%2C%20990%5C%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='M15 = \{15, 30, 45, 60, 75, 90, ..., 975, 990\}' title='M15 = \{15, 30, 45, 60, 75, 90, ..., 975, 990\}' class='latex' /><br />
<br />
<i>M15 terá um total de 66 elementos (999 / 15)</i></p>
<p>M15 então é um subconjunto de M3 e também um subconjunto de M5. (Pode-se dizer que M15 está contido em M3 e em M5).</p>
<p>O problema propõe a soma de todos os números múltiplos de 3 <b>OU</b> 5, então precisamos remover o subconjunto M15 de um dos dois conjuntos (M3 ou M5).<br />
Por quê?</p>
<p>Imagine que o problema pedisse a soma de todos os múltiplos de 3 ou 5 abaixo de 20. Teriamos os seguintes conjuntos:<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=M3%20%3D%20%5C%7B3%2C%206%2C%209%2C%2012%2C%20%7B%5Cbf15%7D%2C%2018%5C%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='M3 = \{3, 6, 9, 12, {\bf15}, 18\}' title='M3 = \{3, 6, 9, 12, {\bf15}, 18\}' class='latex' /><br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=M5%20%3D%20%5C%7B5%2C%2010%2C%20%7B%5Cbf15%7D%5C%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='M5 = \{5, 10, {\bf15}\}' title='M5 = \{5, 10, {\bf15}\}' class='latex' /><br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=M15%20%3D%20%5C%7B15%5C%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='M15 = \{15\}' title='M15 = \{15\}' class='latex' /><br />
</p>
<p>Se realizarmos a somatória de todos os elementos de M3 e M5 a resposta estará incorreta, pois o valor 15 foi somado duas vezes a resposta final, uma vez na somatória dos elementos de M3 e uma vez na somatória de M5.<br />
A solução então é somar M3 a M5 e subtrair M15, fazendo com que o subconjunto M15 seja removido de um dos dois conjuntos.<br />
Então a equação para resolução do problema é:<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=%5Csum%20M3%20%2B%20%5Csum%20M5%20-%20%5Csum%20M15&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\sum M3 + \sum M5 - \sum M15' title='\sum M3 + \sum M5 - \sum M15' class='latex' /><br />
<br />
Não é muito prático realizarmos essa soma na mão, já que ela é composta de muitos números. Olhando bem para as fórmulas, podemos descrever os conjuntos da seguinte maneira:</p>
<ul>
<li>O conjunto M3 é a somatória dos primeiros 333 números múltiplos de 3.</li>
<li>O conjunto M5 é a somatória dos primeiros 199 números múltiplos de 5.</li>
<li>O conjunto M15 é a somatória dos primeiros 66 números múltiplos de 15.</li>
</ul>
<p>Em termos matemáticos:<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=%5Csum_%7Bi%20%3D%201%7D%5E%7B333%7D3%2Ai&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\sum_{i = 1}^{333}3*i' title='\sum_{i = 1}^{333}3*i' class='latex' /><br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=%5Csum_%7Bi%20%3D%201%7D%5E%7B199%7D5%2Ai&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\sum_{i = 1}^{199}5*i' title='\sum_{i = 1}^{199}5*i' class='latex' /><br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=%5Csum_%7Bi%20%3D%201%7D%5E%7B66%7D15%2Ai&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\sum_{i = 1}^{66}15*i' title='\sum_{i = 1}^{66}15*i' class='latex' /><br />
<br />
Se expandirmos a primeira equação, teremos algo como:<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=%283%2A1%29%20%2B%20%283%2A2%29%20%2B%20%283%2A3%29%20%2B%20%283%2A4%29%20%2B%20...%20%2B%20%283%2A332%29%20%2B%20%283%2A333%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='(3*1) + (3*2) + (3*3) + (3*4) + ... + (3*332) + (3*333)' title='(3*1) + (3*2) + (3*3) + (3*4) + ... + (3*332) + (3*333)' class='latex' /><br />
<br />
Todos os elementos estão sendo multiplicados por 3, logo, pode-se colocar o 3 em evidência e teremos:<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=3%2A%281%2B2%2B3%2B4%2B...%2B332%2B333%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='3*(1+2+3+4+...+332+333)' title='3*(1+2+3+4+...+332+333)' class='latex' /><br />
<br />
Que pode ser representado por:<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=3%2A%5Csum_%7Bi%20%3D%201%7D%5E%7B333%7Di&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='3*\sum_{i = 1}^{333}i' title='3*\sum_{i = 1}^{333}i' class='latex' /><br />
</p>
<p>Esse é um resultado bastante interessante pois foi postulado por Gauss (e várias demonstrações do porque podem ser encontradas <a href="http://betterexplained.com/articles/techniques-for-adding-the-numbers-1-to-100/" target="_blank">aqui</a>) que a somatória dos n primeiros números pode ser escrita da seguinte maneira:<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=%5Csum_%7Bi%20%3D%201%7D%5En%20%3D%20n%2A%28n%2B1%29%2F2&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\sum_{i = 1}^n = n*(n+1)/2' title='\sum_{i = 1}^n = n*(n+1)/2' class='latex' /><br />
<br />
Logo, temos a seguinte equação:<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=%283%2A%5Csum_%7Bi%20%3D%201%7D%5E%7B333%7Di%20%2B%205%2A%5Csum_%7Bi%20%3D%201%7D%5E%7B199%7D%29%20-%2015%2A%5Csum_%7Bi%20%3D%201%7D%5E%7B66%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='(3*\sum_{i = 1}^{333}i + 5*\sum_{i = 1}^{199}) - 15*\sum_{i = 1}^{66}' title='(3*\sum_{i = 1}^{333}i + 5*\sum_{i = 1}^{199}) - 15*\sum_{i = 1}^{66}' class='latex' /><br />
<br />
Que pode ser escrita da seguinte maneira:<br />
<br />
<img src='http://s.wordpress.com/latex.php?latex=%283%2A%28333%2A%28333%2B1%29%2F2%29%20%2B%205%2A%28199%2A%28199%2B1%29%2F2%29%29%20-%2015%2A%2866%2A%2866%2B1%29%2F2%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='(3*(333*(333+1)/2) + 5*(199*(199+1)/2)) - 15*(66*(66+1)/2)' title='(3*(333*(333+1)/2) + 5*(199*(199+1)/2)) - 15*(66*(66+1)/2)' class='latex' /><br />
</p>
<p>Isso resulta em: <b>233168</b></p>
<p>E está ai então a resolução matemática.</p>
<p><b> A solução com programação </b></p>
<p>Solução onde não se usam os conceitos matemáticos apresentados acima:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">&nbsp;
<span style="color: #339933;">#include &lt;stdio.h&gt;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> argc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">**</span>argv<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> resultado <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">1000</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>i<span style="color: #339933;">%</span><span style="color:#800080;">3</span> <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span> <span style="color: #009900;">&#40;</span>i<span style="color: #339933;">%</span><span style="color:#800080;">5</span> <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
            resultado <span style="color: #339933;">+=</span> i<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Resultado: %d<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> resultado<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Solução onde os conceitos matemáticos acima são utilizados:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">&nbsp;
<span style="color: #339933;">#include &lt;stdio.h&gt;</span>
&nbsp;
<span style="color: #993333;">int</span> gauss<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> n<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">return</span> <span style="color: #009900;">&#40;</span>n<span style="color: #339933;">*</span><span style="color: #009900;">&#40;</span>n<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">/</span><span style="color: #0000dd;">2</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> argc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">**</span>argv<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">int</span> resultado<span style="color: #339933;">;</span>
&nbsp;
    resultado <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #0000dd;">3</span><span style="color: #339933;">*</span>gauss<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">333</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000dd;">5</span><span style="color: #339933;">*</span>gauss<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">199</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> <span style="color: #0000dd;">15</span><span style="color: #339933;">*</span>gauss<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">66</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Resultado: %d<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> resultado<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.gilgalab.com.br/2011/01/19/project-euler-problema-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Radix Sort</title>
		<link>http://www.gilgalab.com.br/2009/09/19/radix-sort/</link>
		<comments>http://www.gilgalab.com.br/2009/09/19/radix-sort/#comments</comments>
		<pubDate>Sat, 19 Sep 2009 17:05:44 +0000</pubDate>
		<dc:creator>Henrique</dc:creator>
				<category><![CDATA[C]]></category>
		<category><![CDATA[radix]]></category>
		<category><![CDATA[sort]]></category>

		<guid isPermaLink="false">http://www.gilgalab.com.br/?p=59</guid>
		<description><![CDATA[Estive lendo sobre alguns algoritmos de organização e me deparei com o Radix Sort. Pela definição da NIST: Definition: A multiple pass distribution sort algorithm that distributes each item to a bucket according to part of the item's key beginning with the least significant part of the key. After each pass, items are collected from [...]]]></description>
			<content:encoded><![CDATA[<p>Estive lendo sobre alguns algoritmos de organização e me deparei com o Radix Sort.<br />
Pela definição da NIST:</p>
<p><quote><br />
<b>Definition:</b> A multiple pass distribution sort algorithm that distributes each item to a bucket according to part of the item's key beginning with the least significant part of the key. After each pass, items are collected from the buckets, keeping the items in order, then redistributed according to the next most significant part of the key.<br />
</quote></p>
<p>Tradução livre:<br />
<b>Definição:</b> Um algorítmo de organização de vários passos que distribui cada item para um bucket de acordo com parte da chave do item, começando pela parte menos significativa da chave. Após cada passo, os items são recolhidos dos buckets, mantendo os itens em ordem e então redistribuindo de acordo com a próxima parte mais significativa da chave.</p>
<p>Pelas leituras que fiz por aí, um método que me pareceu bastante interessante é aplicar esse algorítmo a cada bit da nossa informação. É claro que isso vai depender da aplicação do algorítmo. No caso que irei trabalhar aqui, estaremos ordenando um vetor com números inteiros positivos.</p>
<p>Vamos supor o seguinte array:</p>
<p>int vetor = {12,22,13,16,31}</p>
<p>Descrevendo cada um desses valores em binário:<br />
12 - 01100<br />
22 - 10110<br />
13 - 01101<br />
16 - 10000<br />
31 - 11111</p>
<p>Pela descrição do algorítmo e pelo método adotado, devemos começar organizando nossa informação pelo bit menos significativo de cada um dos números em nosso array, ou seja, pegamos o bit mais a direita do array e distribuímos os valores em 2 buckets. O bucket onde o bit que estamos olhando é 0 ou ou bucket onde o bit que estamos olhando é 1. Ilustrando isso, temos:</p>
<p>0110<b style="text-weight: bolder; color:red;">0</b> - 12<br />
1011<b style="text-weight: bolder; color:red;">0</b> - 22<br />
0110<b style="text-weight: bolder; color:red;">1</b> - 13<br />
1000<b style="text-weight: bolder; color:red;">0</b> - 16<br />
1111<b style="text-weight: bolder; color:red;">1</b> - 31</p>
<p>Começamos olhando para os bits que estão em negrito. Quando encontrarmos um bit 0, jogamos aquele número para o bucket0. Quando encontrarmos um bit 1, jogamos aquele número para o bucket1. Nossos buckets estão dessa forma agora então:</p>
<p>bucket0 = {12, 22, 16}<br />
bucket1 = {13, 31}</p>
<p>Agora nós devolvemos os valores para dentro do nosso vetor na ordem em que se encontram dentro dos bukets. Primeiro colocamos dentro do vetor todos os valores do bucket0 e depois todos os valores do bucket1. Nosso vetor ficará da seguinte maneira:</p>
<p>vetor = {12, 22, 16, 13, 31}</p>
<p>Agora nós repetimos o processo para o nosso novo vetor, utilizando o próximo bit mais significativo.</p>
<p>011<b style="text-weight: bolder; color:red;">0</b>0 - 12<br />
101<b style="text-weight: bolder; color:red;">1</b>0 - 22<br />
100<b style="text-weight: bolder; color:red;">0</b>0 - 16<br />
011<b style="text-weight: bolder; color:red;">0</b>1 - 13<br />
111<b style="text-weight: bolder; color:red;">1</b>1 - 31</p>
<p>Nossos buckets ficam:</p>
<p>bucket0 = {12, 16, 13}<br />
bucket1 = {22, 31}</p>
<p>Nosso novo vetor:</p>
<p>vetor = {12, 16, 13, 22, 31}</p>
<p>Repetimos o processo para o próximo bit mais significativo em nosso novo vetor:</p>
<p>01<b style="text-weight: bolder; color:red;">1</b>00 - 12<br />
10<b style="text-weight: bolder; color:red;">0</b>00 - 16<br />
01<b style="text-weight: bolder; color:red;">1</b>01 - 13<br />
11<b style="text-weight: bolder; color:red;">0</b>10 - 22<br />
11<b style="text-weight: bolder; color:red;">1</b>11 - 31</p>
<p>Nossos buckets ficam:</p>
<p>bucket0 = {16, 22}<br />
bucket1 = {12, 13, 31}</p>
<p>Nosso novo vetor:</p>
<p>vetor = {16, 22, 12, 13, 31}</p>
<p>Repetimos o processo para o próximo bit mais significativo em nosso novo vetor:</p>
<p>1<b style="text-weight: bolder; color:red;">0</b>000 - 16<br />
1<b style="text-weight: bolder; color:red;">1</b>010 - 22<br />
0<b style="text-weight: bolder; color:red;">1</b>100 - 12<br />
0<b style="text-weight: bolder; color:red;">1</b>101 - 13<br />
1<b style="text-weight: bolder; color:red;">1</b>111 - 31</p>
<p>Nossos buckets ficam:</p>
<p>bucket0 = {16}<br />
bucket1 = {22, 12, 13, 31}</p>
<p>Nosso novo vetor:</p>
<p>vetor = {16,22,12,13,31}</p>
<p>Até então não parece nada arrumado não é mesmo? Mas o útimo passo vai nos revelar algo fantástico! :D</p>
<p>Repetimos o processo para o próximo bit mais significativo em nosso novo vetor:</p>
<p><b style="text-weight: bolder; color:red;">1</b>0000 - 16<br />
<b style="text-weight: bolder; color:red;">1</b>1010 - 22<br />
<b style="text-weight: bolder; color:red;">0</b>1100 - 12<br />
<b style="text-weight: bolder; color:red;">0</b>1101 - 13<br />
<b style="text-weight: bolder; color:red;">1</b>1111 - 31</p>
<p>Nossos buckets ficam:</p>
<p>bucket0 = {12, 13}<br />
bucket1 = {16, 22, 31}</p>
<p>Nosso novo (e último) vetor:</p>
<p>vetor = {12, 13, 16, 22, 31}</p>
<p>Aha! Fantástico!</p>
<p>O mais interessante disso tudo é a velocidade desse algorítmo. Em alguns testes que fiz aqui, consegui organizar 20 milhoes de números em apenas 9,3 segundos!<br />
Irei demonstrar a seguir uma versão um pouco mais lenta do algorítmo que desenvolvi porém de mais fácil entendimento. Logo após irei demonstrar a versão do mesmo algorítmo que foi capaz de organizar 100 milhões de números em 15,56 segundos.</p>
<p><b>O algorítmo 'simples'</b></p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;stdio.h&gt;</span>
<span style="color: #339933;">#include &lt;stdlib.h&gt;</span>
<span style="color: #339933;">#include &lt;time.h&gt;</span>
&nbsp;
<span style="color: #993333;">typedef</span> <span style="color: #993333;">struct</span> lista <span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">int</span> num<span style="color: #339933;">;</span>
    <span style="color: #993333;">struct</span> lista <span style="color: #339933;">*</span>prox<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> lista<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #993333;">void</span> radix_sort<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*,</span> <span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">void</span> insere<span style="color: #009900;">&#40;</span>lista <span style="color: #339933;">**,</span> <span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> pop<span style="color: #009900;">&#40;</span>lista <span style="color: #339933;">**</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">void</span> imprime<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vetor<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> tamanho<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">int</span> tamanho <span style="color: #339933;">=</span> <span style="color: #0000dd;">20</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> vetor<span style="color: #009900;">&#91;</span>tamanho<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
&nbsp;
    srand<span style="color: #009900;">&#40;</span>time<span style="color: #009900;">&#40;</span>NULL<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> tamanho<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        vetor<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> rand<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> tamanho<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    imprime<span style="color: #009900;">&#40;</span>vetor<span style="color: #339933;">,</span> tamanho<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    radix_sort<span style="color: #009900;">&#40;</span>vetor<span style="color: #339933;">,</span> tamanho<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    imprime<span style="color: #009900;">&#40;</span>vetor<span style="color: #339933;">,</span> tamanho<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> insere<span style="color: #009900;">&#40;</span>lista <span style="color: #339933;">**</span>l<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> valor<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    lista <span style="color: #339933;">*</span>aux <span style="color: #339933;">=</span> <span style="color: #339933;">*</span>l<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>l <span style="color: #339933;">==</span> NULL<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #339933;">*</span>l <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>lista <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>malloc<span style="color: #009900;">&#40;</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span>lista<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>l<span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span>num <span style="color: #339933;">=</span> valor<span style="color: #339933;">;</span>
        <span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>l<span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span>prox <span style="color: #339933;">=</span> NULL<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>aux<span style="color: #339933;">-&gt;</span>prox <span style="color: #339933;">!=</span> NULL<span style="color: #009900;">&#41;</span> aux <span style="color: #339933;">=</span> aux<span style="color: #339933;">-&gt;</span>prox<span style="color: #339933;">;</span>
        aux<span style="color: #339933;">-&gt;</span>prox <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>lista <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>malloc<span style="color: #009900;">&#40;</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span>lista<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        aux <span style="color: #339933;">=</span> aux<span style="color: #339933;">-&gt;</span>prox<span style="color: #339933;">;</span>
        aux<span style="color: #339933;">-&gt;</span>num <span style="color: #339933;">=</span> valor<span style="color: #339933;">;</span>
        aux<span style="color: #339933;">-&gt;</span>prox <span style="color: #339933;">=</span> NULL<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> pop<span style="color: #009900;">&#40;</span>lista <span style="color: #339933;">**</span>l<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">int</span> ret<span style="color: #339933;">;</span>
    lista <span style="color: #339933;">*</span>aux<span style="color: #339933;">;</span>
&nbsp;
    ret <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>l<span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span>num<span style="color: #339933;">;</span>
    aux <span style="color: #339933;">=</span> <span style="color: #339933;">*</span>l<span style="color: #339933;">;</span>
    <span style="color: #339933;">*</span>l <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>l<span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span>prox<span style="color: #339933;">;</span>
    free<span style="color: #009900;">&#40;</span>aux<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> ret<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> radix_sort<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vetor<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> tamanho<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
&nbsp;
    lista <span style="color: #339933;">*</span>bucket0 <span style="color: #339933;">=</span> NULL<span style="color: #339933;">;</span>
    lista <span style="color: #339933;">*</span>bucket1 <span style="color: #339933;">=</span> NULL<span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> i<span style="color: #339933;">,</span> j<span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> numero_bits<span style="color: #339933;">;</span>
&nbsp;
    numero_bits <span style="color: #339933;">=</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> <span style="color: #0000dd;">8</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> numero_bits<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>j <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> j <span style="color: #339933;">&lt;</span> tamanho<span style="color: #339933;">;</span> j<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>vetor<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span> <span style="color: #339933;">&gt;&gt;</span> i<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span> <span style="color: #208080;">0xf</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> <span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
                insere<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>bucket0<span style="color: #339933;">,</span> vetor<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #b1b100;">else</span>
                insere<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>bucket1<span style="color: #339933;">,</span> vetor<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        j <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>bucket0 <span style="color: #339933;">!=</span> NULL<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            vetor<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> pop<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>bucket0<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            j<span style="color: #339933;">++;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
        <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>bucket1 <span style="color: #339933;">!=</span> NULL<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            vetor<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> pop<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>bucket1<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            j<span style="color: #339933;">++;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> imprime<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vetor<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> tamanho<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> tamanho<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%d &quot;</span><span style="color: #339933;">,</span> vetor<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><a href="wp-content/uploads/2009/09/radix.c" target="_blank">[radix.c]</a></p>
<p>Essa é a versão 'simples' do algorítmo. Ele utiliza listas para ficar mais simples a inserção e remoção dos registros de nossos buckets. O problema com isso é que conforme aumentamos a quantidade de elementos que queremos organizar o programa fica mais lento. A verdadeira função de ordenação aqui é a função 'radix_sort'. As outras funções fazem parte da implementação da lista.<br />
Vamos então dar uma olhada no programa.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">...
    <span style="color: #993333;">int</span> tamanho <span style="color: #339933;">=</span> <span style="color: #0000dd;">20</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> vetor<span style="color: #009900;">&#91;</span>tamanho<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
&nbsp;
    srand<span style="color: #009900;">&#40;</span>time<span style="color: #009900;">&#40;</span>NULL<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> tamanho<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        vetor<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> rand<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> tamanho<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
...</pre></div></div>

<p>Simplesmente declaramos um array com 20 posições e colocamos números randomicos nele que vão de 0 a 19. Esse é o vetor que desejamos ordenar.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">void</span> radix_sort<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vetor<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> tamanho<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
&nbsp;
    lista <span style="color: #339933;">*</span>bucket0 <span style="color: #339933;">=</span> NULL<span style="color: #339933;">;</span>
    lista <span style="color: #339933;">*</span>bucket1 <span style="color: #339933;">=</span> NULL<span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> i<span style="color: #339933;">,</span> j<span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> numero_bits<span style="color: #339933;">;</span>
&nbsp;
    numero_bits <span style="color: #339933;">=</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> <span style="color: #0000dd;">8</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> numero_bits<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #666666; font-style: italic;">// Primeiro loop</span>
        <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>j <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> j <span style="color: #339933;">&lt;</span> tamanho<span style="color: #339933;">;</span> j<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #666666; font-style: italic;">// Segundo loop</span>
            <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>vetor<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span> <span style="color: #339933;">&gt;&gt;</span> i<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span> <span style="color: #208080;">0xf</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> <span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
                insere<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>bucket0<span style="color: #339933;">,</span> vetor<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #b1b100;">else</span>
                insere<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>bucket1<span style="color: #339933;">,</span> vetor<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        j <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>bucket0 <span style="color: #339933;">!=</span> NULL<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            vetor<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> pop<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>bucket0<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            j<span style="color: #339933;">++;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
        <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>bucket1 <span style="color: #339933;">!=</span> NULL<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            vetor<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> pop<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>bucket1<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            j<span style="color: #339933;">++;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Como na explicação sobre o algorítmo, estou usando aqui 2 buckets e o vetor com os dados. O bucket0 recebe os números cujo bit atual sendo verificado é 0, e o bucket 1 recebe os números cujo bit atual sendo verificado é 1.<br />
A variável 'numero_bits' se refere a quantos bits nós iremos verificar para realizar a ordenação. No caso como estamos organizando números inteiros, em teoria (mais tarde discutirei uma maneira melhor de determinar esse número) faz sentido percorremos todos os bits do mesmo. sizeof(int) retorna o número de bytes de um int, se multiplicamos esse valor por 8 temos o número de bits.<br />
O primeiro loop se refere a qual bit estamos olhando e o segundo loop passa por cada elemento para determinar se o bit é 0 ou 1 e jogar o número em seu respectivo bucket.<br />
Acredito que a linha que mais chama a atenção aqui é a linha 13. Vamos a explicação então! Imagine que estou trabalhando com um número de 4 bits apenas que se encontra em vetor[0]. O que essa linha faz é pegar o número inteiro e fazer uma lógica AND com o valor 0xf (eu poderia ter usado 0x1). Suponhamos que o numero no nosso vetor é 4. Então a lógica fica assim:</p>
<p>Deslocar o valor dentro de vetor[0] para a direita em 0 bits (primeira interação).<br />
Em hexa: 0x4 &#038; 0xf<br />
Em binario: 010<b style="text-weight: bolder; color:red;">0</b> &#038; 111<b style="text-weight: bolder; color:red;">1</b><br />
Resultado: 0100</p>
<p>Deslocar o valor dentro de vetor[0] para a direita em 1 bit (segunda interação).<br />
Em hexa: 0x2 &#038; 0xf<br />
Em binario: 001<b style="text-weight: bolder; color:red;">0</b> &#038; 111<b style="text-weight: bolder; color:red;">1</b><br />
Resultado: 0010</p>
<p>Deslocar o valor dentro de vetor[0] para a direita em 2 bits (terceira interação).<br />
Em hexa: 0x1 &#038; 0xf<br />
Em binario: 000<b style="text-weight: bolder; color:red;">1</b> &#038; 111<b style="text-weight: bolder; color:red;">1</b><br />
Resultado: 0001</p>
<p>Deslocar o valor dentro de vetor[0] para a direita em 3 bits (quarta interação).<br />
Em hexa: 0x0 &#038; 0xf<br />
Em binario: 000<b style="text-weight: bolder; color:red;">0</b> &#038; 111<b style="text-weight: bolder; color:red;">1</b><br />
Resultado: 0000</p>
<p>O que nos interessa aqui é o bit menos significativo, ou seja, o bit mais a direita. Quando realizamos essa lógica AND, o último bit será 0 ou 1. Se o último bit for 0, temos um número par e então o número deve ser colocado no bucket0. Se o último bit for 1, temos um número ímpar e então o número deve ser colocado no bucket1. O deslocamento que fazemos para a direita é apenas para colocar o bit que desejamos verificar na posição menos significativa do número para que possamos saber se ele deve ir ao bucket0 ou ao bucket1.<br />
A lógica que segue é apenas referente a 'remontar' o vetor com todos os valores que estão no bucket0 e depois todos os valores que estão no bucket1.</p>
<p><b>O algorítmo um pouco menos simples</b></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;stdio.h&gt;</span>
<span style="color: #339933;">#include &lt;stdlib.h&gt;</span>
<span style="color: #339933;">#include &lt;time.h&gt;</span>
<span style="color: #339933;">#include &lt;math.h&gt;</span>
&nbsp;
<span style="color: #993333;">void</span> radix_sort<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*,</span> <span style="color: #993333;">int</span><span style="color: #339933;">,</span> <span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">void</span> imprime<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vetor<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> tamanho<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">int</span> tamanho <span style="color: #339933;">=</span> <span style="color: #0000dd;">20</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vetor<span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> maior <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
    clock_t inicio<span style="color: #339933;">,</span> fim<span style="color: #339933;">;</span>
    <span style="color: #993333;">float</span> periodo<span style="color: #339933;">;</span>
&nbsp;
    vetor <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>malloc<span style="color: #009900;">&#40;</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span>tamanho<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    srand<span style="color: #009900;">&#40;</span>time<span style="color: #009900;">&#40;</span>NULL<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> tamanho<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        vetor<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>rand<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> tamanho<span style="color: #009900;">&#41;</span><span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>vetor<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">&gt;</span> maior<span style="color: #009900;">&#41;</span>
            maior <span style="color: #339933;">=</span> vetor<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    imprime<span style="color: #009900;">&#40;</span>vetor<span style="color: #339933;">,</span> tamanho<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    inicio <span style="color: #339933;">=</span> clock<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    radix_sort<span style="color: #009900;">&#40;</span>vetor<span style="color: #339933;">,</span> tamanho<span style="color: #339933;">,</span> maior<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    fim <span style="color: #339933;">=</span> clock<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    periodo <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">float</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">float</span><span style="color: #009900;">&#41;</span>fim<span style="color: #339933;">-</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">float</span><span style="color: #009900;">&#41;</span>inicio<span style="color: #009900;">&#41;</span><span style="color: #339933;">/</span>CLOCKS_PER_SEC<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Tempo: %.15f<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> periodo<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    imprime<span style="color: #009900;">&#40;</span>vetor<span style="color: #339933;">,</span> tamanho<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> radix_sort<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vetor<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> tamanho<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> maior<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #993333;">int</span> i<span style="color: #339933;">,</span> j<span style="color: #339933;">,</span> k<span style="color: #339933;">,</span> l<span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> numero_bits<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #993333;">int</span> <span style="color: #339933;">**</span>temp<span style="color: #339933;">;</span>
&nbsp;
    temp <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">**</span><span style="color: #009900;">&#41;</span>malloc<span style="color: #009900;">&#40;</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    temp<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>malloc<span style="color: #009900;">&#40;</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span>tamanho<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    temp<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>malloc<span style="color: #009900;">&#40;</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span>tamanho<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    numero_bits <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>log<span style="color: #009900;">&#40;</span>maior<span style="color: #009900;">&#41;</span><span style="color: #339933;">/</span>log<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> numero_bits<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        k <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
        l <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>j <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> j <span style="color: #339933;">&lt;</span> tamanho<span style="color: #339933;">;</span> j<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>vetor<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span> <span style="color: #339933;">&gt;&gt;</span> i<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span> <span style="color: #208080;">0xf</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> <span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                temp<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>k<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> vetor<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
                temp<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>l<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> vetor<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        temp<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>k<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #ff0000;">'0'</span><span style="color: #339933;">;</span>
        temp<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>l<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #ff0000;">'0'</span><span style="color: #339933;">;</span>
&nbsp;
        j <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>temp<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span> <span style="color: #339933;">!=</span> <span style="color: #ff0000;">'0'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            vetor<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> temp<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
            j<span style="color: #339933;">++;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        k<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>temp<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>k<span style="color: #009900;">&#93;</span> <span style="color: #339933;">!=</span> <span style="color: #ff0000;">'0'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            vetor<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> temp<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>k<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
            j<span style="color: #339933;">++;</span>
            k<span style="color: #339933;">++;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> imprime<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vetor<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> tamanho<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> tamanho<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%d &quot;</span><span style="color: #339933;">,</span> vetor<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p><a href="wp-content/uploads/2009/09/radix2.c" target="_blank">[radix2.c]</a></p>
<p>Considerações:</p>
<ul>
<li>Essa implementação do algorítmo é apenas para números maiores que 0</li>
<li>Para compilar com o gcc nçao esqueça de compilar o código com -lm para a biblioteca math</li>
</ul>
<p>As chamadas feitas para a função clock() antes e depois da chamada de radix_sort() são para que possamos visualizar quanto tempo a execução do algorítmo levou.<br />
A primeira pequena diferença que vemos nesse código é na linha 12, onde agora declaramos nossa variável vetor como um ponteiro para que possamos alocar o espaço necessário para ela em runtime. Isso se faz necessário pois quando executarmos o programa para organizar 20 milhões de registros, não seria possível alocar o espaço necessário na stack.<br />
A segunda pequena diferença que vemos nesse código está na linha 22, onde garantimos que o número sorteado é no mínimo 1.<br />
A terceira pequena diferença é que agora nós já identificamos qual é o maior número do nosso vetor. Isso será útil mais a frente.<br />
As grandes diferenças começam dentro da função radix_sort().<br />
A primeira coisa para se notar é que não usamos mais listas. Inserir e retirar items de um array é mais rápido, logo é isso que usaremos. Nosso bucket agora é a variável temp; temp[0] é o bucket0 e temp[1] é o bucket1.<br />
A segunda coisa a se notar é a forma de como calculamos o numero de bits. Essa linha é de extrema imoprtância pois ela reflete diretamente na perfomance do algorítmo. Suponha que estamos trabalhando em uma plataforma onde a variável int tem 32 bits. Suponha também que o maior número que se encontra em nosso array é o número 230.<br />
Vamos representar então o número 230 em binário:<br />
000000000000000000000000<b style="text-weight: bolder; color:red;">11100110</b></p>
<p>São 32 bits, apenas 8 bits significativos e 24 bits não significativos. A partir do momento que organizamos os números usando todos os bits significativos é inútil que façamos a verificação para os dígitos não significativos pois eles irão sempre ser colocados no bucket0 e sempre na mesma ordem.<br />
Para entender o cálculo utilizado, precisamos lembrar um pouco da matemática da escola.<br />
2^x = 16<br />
Quanto vale x?<br />
log(base 2) de 16 = x<br />
x = 4</p>
<p>Ou seja, para representarmos 16 números precisamos de 4 bits. Sabemos que o a contagem para os números binários começa em 0, logo com esses 4 bits podemos contar de 0 a 15. Para que o número 16 fosse considerado precisamos adicionar mais 1 bit.<br />
Logo, para representar o número 16 temos: (log(base 2) de 16)+1<br />
Como em C não temos uma forma de calcular log em base 2. nós usamos uma propriedade matemática que diz:</p>
<p>log em base x de y = (log y) / (log x)<br />
Para os que não se lembram log sem menção de base é log em base 10.</p>
<p>Voltando então ao nosso exemplo do número 230. Se calcularmos:<br />
log(base 2) de 230 = x<br />
x = 7,85</p>
<p>Não há possibilidade de termos 0.85 bit. Em C variáveis int se arredondam pra baixo. Logo em nosso caso x vale 7.<br />
2^7 = 128<br />
Não é o suficiente, e matemáticamente falando 7,85 seria arredondado de fato para 8. É por essa razão que somamos 1.<br />
2^8 = 256<br />
Agora sim temos espaço o bastante para o valor 230.</p>
<p>Caso não tenha ficado muito clara a explicação, tente ler novamente e se precisar relembre um pouco de logarítmos. Tenho certeza que ficará mais claro.</p>
<p>O resto da lógica que segue é basicamente o mesmo. Como precisamos de uma forma de identificar quando os números de nosso bucket acabaram, eu optei por dizer que o último número do bucket é 0. É por essa razão que o esse algorítmo só é capaz de organizar números maiores que 0.<br />
Todo o resto é basicamente o mesmo já apresentado antes.</p>
<p><b>Observações</b><br />
Se você testou esses algorítmos deve ter percebido que são bastante rápidos. Eu quis determinar o quão rápida essa segunda implementação apresentada é quando comparada ao quicksort e os resultados são impressionantes.</p>
<p>Eis então os algorítmos usados:</p>
<p><b>Quicksort</b></p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;stdio.h&gt;</span>
<span style="color: #339933;">#include &lt;stdlib.h&gt;</span>
<span style="color: #339933;">#include &lt;time.h&gt;</span>
<span style="color: #339933;">#include &lt;string.h&gt;</span>
&nbsp;
<span style="color: #993333;">void</span> quicksort<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> left<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> right<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> <span style="color: #339933;">*</span>v<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">void</span> swap<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> i<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> j<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> <span style="color: #339933;">**</span>v<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> argc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">**</span>argv<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #993333;">int</span> MAX<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>argc <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Use: %s numero<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> argv<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	MAX<span style="color: #339933;">=</span> atoi<span style="color: #009900;">&#40;</span>argv<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
	<span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vetor<span style="color: #339933;">;</span>
    clock_t inicio<span style="color: #339933;">,</span> fim<span style="color: #339933;">;</span>
    <span style="color: #993333;">float</span> periodo<span style="color: #339933;">;</span>
&nbsp;
	vetor <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>malloc<span style="color: #009900;">&#40;</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span>MAX<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	srand<span style="color: #009900;">&#40;</span>time<span style="color: #009900;">&#40;</span>NULL<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> MAX<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		vetor<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> rand<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> MAX<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	inicio <span style="color: #339933;">=</span> clock<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>	
	quicksort<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span> MAX<span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">,</span> vetor<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	fim <span style="color: #339933;">=</span> clock<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    periodo <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">float</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">float</span><span style="color: #009900;">&#41;</span>fim<span style="color: #339933;">-</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">float</span><span style="color: #009900;">&#41;</span>inicio<span style="color: #009900;">&#41;</span><span style="color: #339933;">/</span>CLOCKS_PER_SEC<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Tempo: %.15f<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> periodo<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> quicksort<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> left<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> right<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> <span style="color: #339933;">*</span>v<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #993333;">int</span> pivot <span style="color: #339933;">=</span> v<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#40;</span>left<span style="color: #339933;">+</span>right<span style="color: #009900;">&#41;</span><span style="color: #339933;">/</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
	<span style="color: #993333;">int</span> i <span style="color: #339933;">=</span> left<span style="color: #339933;">;</span>
	<span style="color: #993333;">int</span> j <span style="color: #339933;">=</span> right<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> left <span style="color: #339933;">&lt;</span> right <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
		<span style="color: #b1b100;">do</span> <span style="color: #009900;">&#123;</span>
&nbsp;
			<span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span>v<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">&lt;</span> pivot<span style="color: #009900;">&#41;</span> i<span style="color: #339933;">++;</span>
			<span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span>v<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span> <span style="color: #339933;">&gt;</span> pivot<span style="color: #009900;">&#41;</span> j<span style="color: #339933;">--;</span>
&nbsp;
			<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> i <span style="color: #339933;">&lt;=</span> j <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
				swap<span style="color: #009900;">&#40;</span>i<span style="color: #339933;">,</span> j<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>v<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				i<span style="color: #339933;">++;</span>
				j<span style="color: #339933;">--;</span>
			<span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
		<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span> i <span style="color: #339933;">&lt;=</span> j <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		quicksort<span style="color: #009900;">&#40;</span>left<span style="color: #339933;">,</span> j<span style="color: #339933;">,</span> v<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		quicksort<span style="color: #009900;">&#40;</span>i<span style="color: #339933;">,</span> right<span style="color: #339933;">,</span> v<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> swap<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> i<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> j<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> <span style="color: #339933;">**</span>v<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #993333;">int</span> aux<span style="color: #339933;">;</span>
&nbsp;
	aux <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>v<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>v<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>v<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>v<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> aux<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><b>Radixsort</b></p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;stdio.h&gt;</span>
<span style="color: #339933;">#include &lt;stdlib.h&gt;</span>
<span style="color: #339933;">#include &lt;time.h&gt;</span>
<span style="color: #339933;">#include &lt;math.h&gt;</span>
&nbsp;
<span style="color: #993333;">void</span> radix_sort<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*,</span> <span style="color: #993333;">int</span><span style="color: #339933;">,</span> <span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">void</span> imprime<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vetor<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> tamanho<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> argc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">**</span>argv<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">int</span> tamanho<span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vetor<span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> maior <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
    clock_t inicio<span style="color: #339933;">,</span> fim<span style="color: #339933;">;</span>
    <span style="color: #993333;">float</span> periodo<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>argc <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Use: %s numero<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> argv<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	tamanho <span style="color: #339933;">=</span> atoi<span style="color: #009900;">&#40;</span>argv<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    vetor <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>malloc<span style="color: #009900;">&#40;</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span>tamanho<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    srand<span style="color: #009900;">&#40;</span>time<span style="color: #009900;">&#40;</span>NULL<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> tamanho<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        vetor<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>rand<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> tamanho<span style="color: #009900;">&#41;</span><span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>vetor<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">&gt;</span> maior<span style="color: #009900;">&#41;</span>
            maior <span style="color: #339933;">=</span> vetor<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">//imprime(vetor, tamanho);</span>
    <span style="color: #666666; font-style: italic;">//printf(&quot;\n&quot;);</span>
&nbsp;
    inicio <span style="color: #339933;">=</span> clock<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    radix_sort<span style="color: #009900;">&#40;</span>vetor<span style="color: #339933;">,</span> tamanho<span style="color: #339933;">,</span> maior<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    fim <span style="color: #339933;">=</span> clock<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    periodo <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">float</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">float</span><span style="color: #009900;">&#41;</span>fim<span style="color: #339933;">-</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">float</span><span style="color: #009900;">&#41;</span>inicio<span style="color: #009900;">&#41;</span><span style="color: #339933;">/</span>CLOCKS_PER_SEC<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Tempo: %.15f<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> periodo<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #666666; font-style: italic;">//imprime(vetor, tamanho);</span>
    <span style="color: #666666; font-style: italic;">//printf(&quot;\n&quot;);</span>
&nbsp;
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> radix_sort<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vetor<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> tamanho<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> maior<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #993333;">int</span> i<span style="color: #339933;">,</span> j<span style="color: #339933;">,</span> k<span style="color: #339933;">,</span> l<span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> numero_bits<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #993333;">int</span> <span style="color: #339933;">**</span>temp<span style="color: #339933;">;</span>
&nbsp;
    temp <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">**</span><span style="color: #009900;">&#41;</span>malloc<span style="color: #009900;">&#40;</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    temp<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>malloc<span style="color: #009900;">&#40;</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span>tamanho<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    temp<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>malloc<span style="color: #009900;">&#40;</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span>tamanho<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    numero_bits <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>log<span style="color: #009900;">&#40;</span>maior<span style="color: #009900;">&#41;</span><span style="color: #339933;">/</span>log<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> numero_bits<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        k <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
        l <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>j <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> j <span style="color: #339933;">&lt;</span> tamanho<span style="color: #339933;">;</span> j<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>vetor<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span> <span style="color: #339933;">&gt;&gt;</span> i<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span> <span style="color: #208080;">0xf</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> <span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                temp<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>k<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> vetor<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
                temp<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>l<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> vetor<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        temp<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>k<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #ff0000;">'0'</span><span style="color: #339933;">;</span>
        temp<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>l<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #ff0000;">'0'</span><span style="color: #339933;">;</span>
&nbsp;
        j <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>temp<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span> <span style="color: #339933;">!=</span> <span style="color: #ff0000;">'0'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            vetor<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> temp<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
            j<span style="color: #339933;">++;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        k<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>temp<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>k<span style="color: #009900;">&#93;</span> <span style="color: #339933;">!=</span> <span style="color: #ff0000;">'0'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            vetor<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> temp<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>k<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
            j<span style="color: #339933;">++;</span>
            k<span style="color: #339933;">++;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> imprime<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vetor<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> tamanho<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> tamanho<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%d &quot;</span><span style="color: #339933;">,</span> vetor<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><a href="wp-content/uploads/2009/09/radixsort.c" target="_blank">[Radixsort]</a><br />
<a href="wp-content/uploads/2009/09/quick.c" target="_blank">[Quicksort]</a></p>
<p>Dados da máquina onde o teste foi feito:</p>
<p>$ uname -a<br />
Linux myhost 2.6.30-ARCH #1 SMP PREEMPT Mon Aug 17 16:06:45 CEST 2009 x86_64 Intel(R) Core(TM)2 Duo CPU E7400 @ 2.80GHz GenuineIntel GNU/Linux<br />
4GB Ram DDR2 800MHz</p>
<p>Eis então uma tabela comparativa do tempo de execução dos algorítmos para quando o maior valor que pode existir dentro do vetor é o próprio tamanho do vetor.<br />
O tempo é dado em segundos</p>
<table>
<tr>
<td><b>Numero elementos</b></td>
<td><b>Radix Sort (s)</b></td>
<td><b>Quick Sort (s)</b></td>
</tr>
<tr>
<td>10</td>
<td>0.000000000000000</td>
<td>0.000000000000000</td>
</tr>
<tr>
<td>1000</td>
<td>0.000000000000000</td>
<td>0.000000000000000</td>
</tr>
<tr>
<td>100 mil</td>
<td>0.019999999552965</td>
<td>0.009999999776483</td>
</tr>
<tr>
<td>1 milhão</td>
<td>0.310000002384186</td>
<td>0.219999998807907</td>
</tr>
<tr>
<td>10 milhões</td>
<td>3.759999990463257</td>
<td>2.549999952316284</td>
</tr>
<tr>
<td>100 milhões</td>
<td>42.380001068115234</td>
<td>28.530000686645508</td>
</tr>
</table>
<p>Ao que parece, quicksort vence em todos os testes.<br />
Agora façamos a seguinte alteração nos dois códigos:</p>
<p>No código do quicksort, trocamos</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">		vetor<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> rand<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> MAX<span style="color: #339933;">;</span></pre></div></div>

<p>por</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">		vetor<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> rand<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> <span style="color: #0000dd;">1023</span><span style="color: #339933;">;</span></pre></div></div>

<p>No código do radixsort, trocamos</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">		vetor<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>rand<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> tamanho<span style="color: #009900;">&#41;</span><span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span></pre></div></div>

<p>por</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">		vetor<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>rand<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> <span style="color: #0000dd;">1022</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span></pre></div></div>

<p>Eis os novos resultados:</p>
<table>
<tr>
<td><b>Numero elementos</b></td>
<td><b>Radix Sort (s)</b></td>
<td><b>Quick Sort (s)</b></td>
</tr>
<tr>
<td>10</td>
<td>0.000000000000000</td>
<td>0.000000000000000</td>
</tr>
<tr>
<td>1000</td>
<td>0.000000000000000</td>
<td>0.000000000000000</td>
</tr>
<tr>
<td>100 mil</td>
<td>0.009999999776483</td>
<td>0.009999999776483</td>
</tr>
<tr>
<td>1 milhão</td>
<td>0.159999996423721</td>
<td>0.180000007152557</td>
</tr>
<tr>
<td>10 milhões</td>
<td>1.559999942779541</td>
<td>2.059999942779541</td>
</tr>
<tr>
<td>100 milhões</td>
<td>15.560000419616699</td>
<td>22.809999465942383</td>
</tr>
</table>
<p>O Radixsort vence todas as comparações!<br />
Logo, dependendo do tipo de dados que se deseja ordenar (caracteres por exemplo), o Radixsort pode ter uma performance superior a do Quicksort.</p>
<p>As implementações do Radixsort aqui apresentadas ainda podem ser otimizadas eu acredito, podendo apresentar uma performance ainda maior!</p>
<p><b>Referências</b></p>
<p><a href="http://www.itl.nist.gov/div897/sqg/dads/HTML/radixsort.html" target="_blank">http://www.itl.nist.gov/div897/sqg/dads/HTML/radixsort.html</a><br />
<a href="http://www.jimloy.com/computer/radix.htm" target="_blank">http://www.jimloy.com/computer/radix.htm</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.gilgalab.com.br/2009/09/19/radix-sort/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Lancamento: Dive Into Python 3</title>
		<link>http://www.gilgalab.com.br/2009/09/18/lancamento-dive-into-python-3/</link>
		<comments>http://www.gilgalab.com.br/2009/09/18/lancamento-dive-into-python-3/#comments</comments>
		<pubDate>Fri, 18 Sep 2009 14:00:04 +0000</pubDate>
		<dc:creator>Henrique</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.gilgalab.com.br/?p=53</guid>
		<description><![CDATA[Hoje foi lançado o livro 'Dive Into Python 3' de Mark Pilgrim em formato digital . Ao que parece ele também será comercializado a partir de 16 de outubro. Dei uma lida no primeiro capítulo do livro e me pareceu bom. O autor escreve de forma simples de se entender e começa mostrando código ao [...]]]></description>
			<content:encoded><![CDATA[<p>Hoje foi lançado o livro 'Dive Into Python 3' de Mark Pilgrim em formato digital . Ao que parece ele também será comercializado a partir de 16 de outubro.<br />
Dei uma lida no primeiro capítulo do livro e me pareceu bom. O autor escreve de forma simples de se entender e começa mostrando código ao invés de gastar 75 páginas contando histórinha sobre a linguagem.</p>
<p>Link: <a href="http://diveintopython3.org/?dupe=withhonor">Dive Into Python 3</a></p>
<p>Fonte: <a href="http://www.dzone.com/links/dive_into_python_3_2.html">Dzone</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.gilgalab.com.br/2009/09/18/lancamento-dive-into-python-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Construindo um editor de texto com Java + Swing &#8211; Parte 1</title>
		<link>http://www.gilgalab.com.br/2009/09/13/construindo-um-editor-de-texto-com-java-swing-parte-1/</link>
		<comments>http://www.gilgalab.com.br/2009/09/13/construindo-um-editor-de-texto-com-java-swing-parte-1/#comments</comments>
		<pubDate>Sun, 13 Sep 2009 22:54:54 +0000</pubDate>
		<dc:creator>Henrique</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[swing gui java]]></category>

		<guid isPermaLink="false">http://localhost:8008/wordpress/?p=27</guid>
		<description><![CDATA[É, eu sei que faz tempo que não escrevo. Faltou paciência/tempo/paciência/inspiração/paciência e por ai vai... Bom, estou de volta e atualmente brincando um pouco com Java para construir GUIs (Graphical User Interfaces). Num tutorial que terá sabe-se lá quantas partes vou abordar como criar um editor de texto simples em Java. Esse editor de texto [...]]]></description>
			<content:encoded><![CDATA[<p>É, eu sei que faz tempo que não escrevo. Faltou paciência/tempo/paciência/inspiração/paciência e por ai vai...<br />
Bom, estou de volta e atualmente brincando um pouco com Java para construir GUIs (Graphical User Interfaces). Num tutorial que terá sabe-se lá quantas partes vou abordar como criar um editor de texto simples em Java. Esse editor de texto se propõe (pelo menos por enquanto) a possuir as seguintes funcionalidades:</p>
<ul>
<li>Edição de arquivos em abas</li>
<li>Salvar documentos</li>
<li>Copiar texto através de um menu</li>
<li>Colar texto através de um menu</li>
<li>Mostrar uma caixinha de "Sobre o Editor"</li>
</ul>
<p>É possível que conforme eu vá mexendo no editor e aprendendo truques novos eu adicione coisas novas.<br />
Nessa primeira parte do tutorial irei mostrar os seguintes conceitos:</p>
<ul>
<li>Como criar uma janela com Swing</li>
<li>Como adicionar componentes a janela</li>
<li>Como criar um menu para a janela</li>
<li>Como tratar eventos no seu menu</li>
<li>Como criar um painel com abas</li>
</ul>
<p>Wow! Não imaginei que eram tantos assuntos hehehe. Bom, a intenção aqui é de ser mais um guia e não uma referência completa. Conforme discuto cada assunto, colocarei informações básicas e links apontando para lugares onde pode-se obter maiores informações (basicamente para a Javadoc).<br />
Tendo escrito tanto, hora de ir para a parte interessante da coisa... a programação!</p>
<p><strong>Como criar uma janela com Swing</strong><br />
Rapidamente antes de começar, preciso dizer uma coisinha. Eu estou assumindo que você, leitor, tem ao menos um leve conhecimento de Java (sintaxe e um pouquinho de nada de orientação a objetos). Caso não tenha, pode seguir em frente, mas recomendo ler algum material falando um pouco sobre a linguagem.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.swing.JFrame</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> JanelaSimples <span style="color: #000000; font-weight: bold;">extends</span> <span style="color: #003399;">JFrame</span> <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> JanelaSimples<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">setTitle</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Minha primeira janela&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">setSize</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">640</span>,<span style="color: #cc66cc;">480</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">setVisible</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">setDefaultCloseOperation</span><span style="color: #009900;">&#40;</span>EXIT_ON_CLOSE<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">new</span> JanelaSimples<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><a href="wp-content/uploads/2009/09/JanelaSimples.java" target="_blank">[JanelaSimples.java]</a></p>
<p>Para compilar:<br />
javac JanelaSimples.java</p>
<p>Para executar:<br />
java JanelaSimples</p>
<p>Não coloque a extensão .class ou .java quando for executar a aplicação pois não irá funcionar.</p>
<p>Deu pra ver que é uma janela bastante útil. Você consegue redimensionar, fechar e... e é isso :)<br />
Mesmo não servindo para muita coisa já deu um gostinho, então vamos as partes desse programa.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> JanelaSimples <span style="color: #000000; font-weight: bold;">extends</span> <span style="color: #003399;">JFrame</span> <span style="color: #009900;">&#123;</span></pre></div></div>

<p>Aqui estamos criando a nossa classe JanelaSimples e herdando toda a funcionalidade de JFrame, que é a classe responsável pelos métodos que criam a nossa janela.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">	<span style="color: #000000; font-weight: bold;">public</span> JanelaSimples<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">setTitle</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Minha primeira janela&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">setSize</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">640</span>,<span style="color: #cc66cc;">480</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">setVisible</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">setDefaultCloseOperation</span><span style="color: #009900;">&#40;</span>EXIT_ON_CLOSE<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Em primeiro lugar, todas os métodos que estão sendo invocados foram herdados da classe JFrame, e é por isso que eu os chamo com 'this.'.<br />
O que estes métodos estão fazendo? Na respectiva sequencia:<br />
Definindo o titulo da janela para "Minha primeira janela"<br />
Definindo o tamanho da janela para 640x480<br />
Definindo que a janela deve ser exibida<br />
Definindo que a operação padrão para quando você fechar a janela é a de que o programa deve terminar</p>
<p>Tudo muito simples.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">new</span> JanelaSimples<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Como esse é o nosso programa principal ele precisa de uma função main que serve de ponto de entrada para ele. Nossa função main simplesmente instancia a classe JanelaSimples. Quando a instancia é criada, o construtor (explicado logo acima) é chamado e a nossa janela se faz visível.</p>
<p><strong>Como adicionar componentes a janela</strong></p>
<p>Agora que já sabemos criar a janela, vamos adicionar uma caixa de texto a ela. Para isso, usaremos o mesmo código da JanelaSimples.java e adicionaremos alguns comandos no construtor da classe. O construtora ficará da seguinte maneira:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.swing.JFrame</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.swing.JTextPane</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> JanelaSimples <span style="color: #000000; font-weight: bold;">extends</span> <span style="color: #003399;">JFrame</span> <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> JanelaSimples<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003399;">JTextPane</span> texto <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">JTextPane</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">setTitle</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Minha primeira janela&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">setSize</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">640</span>,<span style="color: #cc66cc;">480</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>texto<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">setVisible</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">setDefaultCloseOperation</span><span style="color: #009900;">&#40;</span>EXIT_ON_CLOSE<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">new</span> JanelaSimples<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><a href="wp-content/uploads/2009/09/JanelaSimples-2.java" target="_blank">[JanelaSimples-2.java]</a></p>
<p>Se quiser compilar este exemplo, renomeie o arquivo para JanelaSimples.java e use as instruções fornecidas acima.<br />
Daqui pra frente eu evitarei re-escrever todo o código o tempo todo e colarei apenas as novas partes que foram adicionadas. Para acessar o código todo, por favor use os arquivos que estão linkados em cada seção :)<br />
Este novo código não mudou muito. As novidades aqui são:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.swing.JTextPane</span><span style="color: #339933;">;</span>
...
		<span style="color: #003399;">JTextPane</span> texto <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">JTextPane</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		...
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>texto<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Adicionei o import referente a classe JTextPane que nos fornece uma caixa de texto. Dentro do construtor eu simplesmente crio uma instancia da class JTextPane e adiciono essa instancia a minha janela. O método 'add()' também foi herdado de JFrame.<br />
Você vai perceber que o componente está usando a janela toda. Isso pode ser mudado, e será discutido quando estivermos falando de layouts da janela.<br />
Todo componente que você desejar criar, basta instancia-lo e então adiciona-lo a janela utilizando o método 'add()'.<br />
Se você deseja maiores informações sobre os métodos que a classe JFrame implementa e seus respectivos protótipos, de uma olhada na documentação do <a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JFrame.html" target="_blank">JFrame</a></p>
<p><strong>Como criar um menu para a janela</strong></p>
<p>Até então tudo muito interessante. Vamos adicionar um pouco de emoção agora e criar um menu para a nossa linda janela que não faz muita coisa.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.swing.JFrame</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.swing.JTextPane</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.swing.JMenuBar</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.swing.JMenu</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.swing.JMenuItem</span><span style="color: #339933;">;</span>
...
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> JanelaSimples<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003399;">JMenuBar</span> barra <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">JMenuBar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003399;">JMenu</span> menuArquivo <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">JMenu</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Arquivo&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003399;">JMenuItem</span> arqSair <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">JMenuItem</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Sair&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		menuArquivo.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>arqSair<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		barra.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>menuArquivo<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">setJMenuBar</span><span style="color: #009900;">&#40;</span>barra<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		...
	<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><a href="wp-content/uploads/2009/09/JanelaSimples-3.java" target="_blank">[JanelaSimples-3.java]</a></p>
<p>E o nosso programa está crescendo!<br />
Só para esclarecer; um menu é feito de basicamente três partes:<br />
A barra de menus<br />
Os menus<br />
Os items dos menus<br />
Como pode-se perceber nós adicionamos três novos imports em nosso código que se referem a cada um desses items. Em nosso construtor então nós instanciamos uma barra de menu (JMenuBar), instanciamos um menu (JMenu) e finalmente instanciamos um item para o menu (JMenuItem). Depois de cada um dos items instanciados e configurados conforme desejamos, basta associa-los conforme feito no código.<br />
Adicionamos o item 'arqSair' dentro do menu 'menuArquivo'. Adicionamos o menu 'menuArquivo' a barra de menu 'barra' e por fim chamamos o método setJMenuBar para adicionar o menu a nossa janela.<br />
Para adicionar o menu nós utilizamos o método especial setJMenuBar pois ele já configura o nosso menu para ser mostrado da maneira esperada no topo da janela.</p>
<p><strong>Como tratar eventos no seu menu</strong></p>
<p>Eu estou achando esse programa cada vez mais empolgante! :D (espero que vocês também)<br />
Como deu pra notar, o nosso menu 'Sair' não faz absolutamente nada :(<br />
Iremos abordar agora um tipo simples de evento, e falar um pouquinho sobre alguns tipos de eventos que existem. Ao longo dos próximos tutoriais de como criar o nosso editor de texto iremos falando mais sobre esse assunto e explorando novos eventos.<br />
Vamos então colocar uma funcionalidade nesse item 'Sair' para que ele faça aquilo que ele promete :)</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">...
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.awt.event.ActionListener</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.awt.event.ActionEvent</span><span style="color: #339933;">;</span>
&nbsp;
...
&nbsp;
		<span style="color: #003399;">JMenuItem</span> arqSair <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">JMenuItem</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Sair&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		arqSair.<span style="color: #006633;">addActionListener</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">ActionListener</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> actionPerformed<span style="color: #009900;">&#40;</span><span style="color: #003399;">ActionEvent</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
				<span style="color: #003399;">System</span>.<span style="color: #006633;">exit</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		menuArquivo.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>arqSair<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		barra.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>menuArquivo<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">setJMenuBar</span><span style="color: #009900;">&#40;</span>barra<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
...</pre></div></div>

<p><a href="wp-content/uploads/2009/09/JanelaSimples-4.java" target="_blank">[JanelaSimples-4.java]</a></p>
<p>Mais dois imports para nos auxiliar e um trecho de código um tanto quanto diferente. Deixe-me falar um pouco sobre eventos e listeners e especialmente sobre o ActionListener e o ActionEvent.<br />
Eventos, como o nome sugere, são coisas que acontecem ao seu programa. Quando o usuário interage com o programa ao clicar em algo, digitar algo, movimentar o mouse ou coisas do genêro, um evento está acontecendo. O nosso programa sabe desses eventos através do chamamos de Listeners.<br />
Os Listeners ficam 'ouvindo' o programa por eventos que aconteçam. Quando um evento acontece, o Listener invoca o método associado ao tipo de evento.<br />
O ActionListener é um Listener para os eventos mais comums, como um clique ou como quando o usuário pressiona Enter ou Space. O evento que é lido por um ActionListener é um ActionEvent. Quando você tem um item em seu menu e clica com o botão direito ou esquerdo nele você gerou um ActionEvent. Se voce selectionar o menu e apertar Enter, você gerou um ActionEvent nele.<br />
Possuindo essa noção de Listener e Event, vamos reanalizar o código acima.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">	arqSair.<span style="color: #006633;">addActionListener</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">ActionListener</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> actionPerformed<span style="color: #009900;">&#40;</span><span style="color: #003399;">ActionEvent</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #003399;">System</span>.<span style="color: #006633;">exit</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>O componente JMenuItem possui um método que nos permite associar a instancia de uma classe que trata eventos do tipo ActionEvent ao seu ActionListener.<br />
Sempre que um ActionEvent acontecer o método 'actionPerformed' dessa instancia será chamado para tratar do evento.<br />
No nosso caso, para não precisarmos escrever toda uma classe para isso, nós criamos uma instancia anonima de ActionListener explicitando o nosso método actionPerfomed. Quando a ação ocorrer, esse método será executado e em nosso caso irá fazer com que a aplicação encerre.<br />
O parametro que o método recebe contém informações sobre o evento, tais como: De onde veio o evento, quando o evento aconteceu, quais teclas estavam pressionadas quando o evento occoreu e etc... Para maiores informações sobre o que se pode tirar do ActionEvent, acesse <a href="http://java.sun.com/javase/6/docs/api/java/awt/event/ActionEvent.html" target="_blank">esse link</a><br />
Com isso, encerramos a breve introdução a eventos. Se ficaram algumas dúvidas, não se preocupe pois iremos falar mais sobre eles no futuro.</p>
<p><strong>Como criar um painel com abas</strong></p>
<p>Nosso editor de texto já está ganhando forma e agora é hora de dar a ele a primeira funcionalidade prometida: Abas!<br />
Vamos criar então um painel de abas onde cada aba será uma caixa de texto diferente para escrevermos.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.swing.JFrame</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.swing.JTextPane</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.swing.JMenuBar</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.swing.JMenu</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.swing.JMenuItem</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.awt.event.ActionListener</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.awt.event.ActionEvent</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// JTabbedPane para nosso painel de abas!</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.swing.JTabbedPane</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> JanelaSimples <span style="color: #000000; font-weight: bold;">extends</span> <span style="color: #003399;">JFrame</span> <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> JanelaSimples<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003399;">JMenuBar</span> barra <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">JMenuBar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003399;">JMenu</span> menuArquivo <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">JMenu</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Arquivo&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003399;">JMenuItem</span> arqSair <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">JMenuItem</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Sair&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		arqSair.<span style="color: #006633;">addActionListener</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">ActionListener</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> actionPerformed<span style="color: #009900;">&#40;</span><span style="color: #003399;">ActionEvent</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
				<span style="color: #003399;">System</span>.<span style="color: #006633;">exit</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		menuArquivo.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>arqSair<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		barra.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>menuArquivo<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">setJMenuBar</span><span style="color: #009900;">&#40;</span>barra<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #003399;">JTextPane</span> texto <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">JTextPane</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">setTitle</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Minha primeira janela&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">setSize</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">640</span>,<span style="color: #cc66cc;">480</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #008000; font-style: italic; font-weight: bold;">/**
		 * A caixa de texto não é mais adicionada a janela
		 * e sim ao painel de abas
		 */</span>
		<span style="color: #666666; font-style: italic;">//this.add(texto); &amp;lt;--- comentado!</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">setDefaultCloseOperation</span><span style="color: #009900;">&#40;</span>EXIT_ON_CLOSE<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #008000; font-style: italic; font-weight: bold;">/**
		 * Criar o painel e adiciona-lo a janela
		 */</span>
		<span style="color: #003399;">JTabbedPane</span> painel <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">JTabbedPane</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		painel.<span style="color: #006633;">addTab</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Aba 1&quot;</span>, texto<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>painel<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">setVisible</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">new</span> JanelaSimples<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><a href="wp-content/uploads/2009/09/JanelaSimples-5.java" target="_blank">[JanelaSimples-5.java]</a></p>
<p>Coloquei o código completo para não nos perdermos. As partes novas estão comentadas para serem mais facilmente identificadas.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">...
&nbsp;
		<span style="color: #666666; font-style: italic;">//this.add(texto); &amp;lt;--- comentado!</span>
&nbsp;
		...
&nbsp;
		<span style="color: #008000; font-style: italic; font-weight: bold;">/**
		 * Criar o painel e adiciona-lo a janela
		 */</span>
		<span style="color: #003399;">JTabbedPane</span> painel <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">JTabbedPane</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		painel.<span style="color: #006633;">addTab</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Aba 1&quot;</span>, texto<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>painel<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		...</pre></div></div>

<p>Até aqui, bastante simples. Criamos um JTabbedPane, que é o nosso painel com abas e adicionamos uma aba com o título "Aba 1" e o componente que ela irá exibir é a nossa caixa de texto. Adicionamos então o painel a janela. Vejam que comentei a linha que adicionava a caixa de texto a janela já que agora a caixa de texto faz parte do painel de abas.</p>
<p><strong>Próximo episódio</strong></p>
<p>Bem pessoal, por hoje é só :)<br />
Na próxima parte iremos abordar os seguintes temas:</p>
<ul>
<li>Criação do menu 'Novo'</li>
<li>Criação do menu 'Salvar'</li>
<li>Criação do menu 'Salvar Como'</li>
<li>Criação do menu 'Sobre'</li>
</ul>
<p>Talvez eu aborde mais coisas, mas não sei ainda.<br />
Até a próxima :)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.gilgalab.com.br/2009/09/13/construindo-um-editor-de-texto-com-java-swing-parte-1/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
	</channel>
</rss>

