<?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>Sean Jordan &#187; C/C++</title>
	<atom:link href="http://seanjordan.me/category/cc/feed/" rel="self" type="application/rss+xml" />
	<link>http://seanjordan.me</link>
	<description>supernerd</description>
	<lastBuildDate>Wed, 25 Aug 2010 06:04:22 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Printing binary trees to stdout in C++</title>
		<link>http://seanjordan.me/2010/03/printing-binary-tree-to-stdout-in-c/</link>
		<comments>http://seanjordan.me/2010/03/printing-binary-tree-to-stdout-in-c/#comments</comments>
		<pubDate>Wed, 17 Mar 2010 07:53:21 +0000</pubDate>
		<dc:creator>Sean Jordan</dc:creator>
				<category><![CDATA[C/C++]]></category>

		<guid isPermaLink="false">http://seanjordan.me/?p=170</guid>
		<description><![CDATA[Have you ever found yourself playing with binary trees, be it for fun, a class, or a real project/work? A class I am enrolled in recently introduced the concept of binary trees, and to help myself confirm my code behaved well, I thought it would be good if I could visually represent my binary trees. [...]]]></description>
			<content:encoded><![CDATA[<p>Have you ever found yourself playing with binary trees, be it for fun, a class, or a real project/work?  A class I am enrolled in recently introduced the concept of binary trees, and to help myself confirm my code behaved well, I thought it would be good if I could visually represent my binary trees.  There is a simple problem with printing binary trees to stdout.  The problem is that you can only print row-by-row.  So you have to print all nodes at depth four in sequence, however the nodes won&#8217;t all share a common immediate parent.  </p>
<p>I solved the problem, by implementing a method to traverse the tree to each specific node.  I liked the solution, so I thought I would share it.</p>
<p>I won&#8217;t go into the code for creating the tree, but let&#8217;s assume our tree is made of nodes that look like this:</p>
<pre name="code" class="c++">
 struct node {
    int data;
    node* parent;
    node* left;
    node* right;
 };
</pre>
<p>The very first problem that you will face is: Where do I place the first node?  You&#8217;ll already know that there is only going to be one node on the first row, so the first row is easy, right?  Well, it&#8217;s not quite that simple.  You have to know how far out to place the node.  In order to have the node centered, you have to know how many nodes will be on the bottom row!</p>
<p>So, I implemented a beautifully simple function to count how many rows the tree has.  It looks like this:</p>
<pre name="code" class="c++">

int num_rows(node* parent) {
   int num_left = 0;
   int num_right = 0;

   if(parent->left != NULL) {
      num_left = num_rows(parent->left);
   }
   if(parent->right != NULL) {
      num_right = num_rows(parent->right);
   }

   if(num_left > num_right) {
      return 1 + num_left;
   } else {
      return 1 + num_right;
   }
}
</pre>
<p>Basically the method recursively counts how many children its children have, and adds one to the total (to include itself in the sum).  Now we know our tree has X number of rows.  Our next task is to compute how many nodes are on the bottomrow.  This is very easy to do.  Since the tree is binary, it grows by powers of 2.  The first row has 2^(1-0) = 2^0 = 1 nodes.  The second row has 2^(2-1) = 2^1 = 2 nodes.  The third row has 2^(3-1) = 2^2 = 4 nodes, etc&#8230;  So, if our tree has 6 rows, we know the 6th and final row has 32 nodes (2^5).  </p>
<p>Now we&#8217;re ready to tackle the next problem for placing the first node, which is getting the spacing exact.  If we just simply place a node, and have its children always the same distance, down and left/right, we very quickly run into an overlapping problem (marked in purple):</p>
<p><img src="http://seanjordan.me/wp-content/uploads/2010/03/bad_alignment.png" alt="Poorly aligned trees overlap nodes" title="Poorly aligned trees overlap nodes" /></p>
<p>To overcome this, we now have to figure out our spacing from the bottom up.  I place the nodes on the bottom row evenly.  The space between the nodes is equal to the width of the space allotted for each node, which must be defined.  If you allot no space for the printing of the node, the spacing will ruined.  I predefine the width of the individual nodes with a constant, and including the iomanip library to control whitespace.</p>
<pre name="code" class="c++">
#define NODE_WIDTH 2
...
cout << setw(NODE_WIDTH) << current_node->data;
</pre>
<p>Draw out the tree from the bottom up, and the pattern should become clear pretty quickly.  Here is an example tree with three rows, properly spaced:</p>
<p><img src="http://seanjordan.me/wp-content/uploads/2010/03/good_alignment.png"  alt="Well aligned trees allow plenty of space for each node"  title="Well aligned trees allow plenty of space for each node" /></p>
<p>The pattern becomes more and more clear when more rows are added.</p>
<p><img src="http://seanjordan.me/wp-content/uploads/2010/03/good_alignment4.png" alt="Well aligned binary tree with four rows" title="Well aligned binary tree with four rows" /></p>
<p>Adding a grid makes it easier to see where the node-widths are located.</p>
<p><img src="http://seanjordan.me/wp-content/uploads/2010/03/good_alignment4_grid.png" alt="Overlaying a grid onto the binary tree makes the spacing obvious" title="Overlaying a grid onto the binary tree makes the spacing obvious" /></p>
<p>From this, I see that the spacing on the bottom row is: NODE, 1 NODE-WIDTH, NODE, 1 NODE-WIDTH, etc..  The next row up is: 1 NODE-WIDTH, NODE, 1 NODE-WIDTH, 1 NODE-WIDTH, 1 NODE-WIDTH, NODE, etc&#8230; The next row up is: 3 NODE-WIDHTS, NODE, 3 NODE-WIDTHS, 1 NODE-WIDTH, 3 NODE-WIDTHS, NODE.</p>
<p>The pattern that should be striking your eye is 0, 1, 3, 7.  Now, where do these numbers come from?  You should see that it is:</p>
<p>0 = (2^0) &#8211; 1<br />
1 = (2^1) &#8211; 1<br />
3 = (2^2) &#8211; 1<br />
7 = (2^3) &#8211; 1</p>
<p>Where {0,1,2,3} are equal to num_rows(parent) &#8211; current_row.  So, if we have a tree of size rows, the magic number for the 4th row is: (2^(6-4)) &#8211; 1 = (2^2) &#8211; 1 = 3.  </p>
<p>We finally know where to place the first node.  We will make (2^(NUM_ROWS-1)) &#8211; 1 NODE-WIDTHs, and print our node&#8217;s value.  </p>
<p>The next great challenge is finding which node to print next.  As a human, I know I will print:<br />
parent,<br />
parent->left, parent->right,<br />
parent->left->left, parent->left->right, parent->right->left, parent->right->right.</p>
<p>Yikes, that is clearly going to be too messy for a computer.  So how do we know which node to print next?  I have a quite simple method for this.  I give each node an imaginary index, based on its location in the tree:</p>
<p><img src="http://seanjordan.me/wp-content/uploads/2010/03/nodes_indices.png" alt="Give the nodes incrementing indices so their locations can be predicted" title="Give the nodes incrementing indices so their locations can be predicted" /></p>
<p>I know where each index is located, because I know which range of numbers will fall on each row.  It is just a binary search to find the right index.  Row 1 starts with index 1, and uses up 1 number.  Row 2 starts with index 2, and uses up 2 numbers (2 &#038; 3).  Row 3 starts with 4, and uses up 4 numbers (4, 5, 6, &#038; 7).  Row 4 starts with 8 and uses up 8 numbers&#8230; etc.  Pretty simple, right?</p>
<p>I wrote a recursive function to seek out a requested node, given a few calculations.  The function looks like this:</p>
<pre name="code" class="c++">

node* seek(node* parent, int index, int a, int b, int currRow, int seekRow) {

   if(parent == NULL) {
	   return NULL;
   }

   int c = floor( (a+b) / 2 );

   node* currNode = NULL;
   if(index <= c) {
      currNode = parent->left;
      b = c;
   } else {
      currNode = parent->right;
      a = c+1;
   }

   if(seekRow == 1) {
      return parent;
   } else if(currRow == (seekRow-1)) {
      if(currNode == NULL) {
         return NULL;
      } else {
         return currNode;
      }
   } else {
      return seek(currNode, index, a, b, currRow+1, seekRow);
   }
}
</pre>
<p>For example, say we are seeking out the node at index #10.  I know 10 is on the 4th row (because 10 falls between 2^(4-1) and 2^(5-1)).  I know the 4th row starts at 8, and ends at 15 ( 2^(4-1), 2^(4-1) + 2^(4-1) &#8211; 1).  So I pass the seek function these parameters:</p>
<p>node* found = seek(parent, 10, 8, 15, 1, 4);</p>
<p>First iteration, the function looks at the index and the range 8-15.  If 10 falls in the lower half of the range, it traverses left 1 node, if 10 falls in the upper half of the range, it traverses right 1 node.  Since currRow = 1 and seekRow = 4, the function will recursively call itself with updated parameters.  </p>
<p>return seek(currNode, 10, 8, 11, 2, 4);</p>
<p>The 15 turns into an 11, because the upper-bound of the range was eliminated (via binary search).  This process continues until the search pinpoints the sought after node index, or reaches a NULL node on the way.  </p>
<p>We now have everything we need to know to print out our binary tree.  The final coding phase is simple.  This requires the cmath and iomanip libraries.  </p>
<pre name="code" class="c++">

//assume parent is the root node a pre-built tree

   int total_rows = num_rows(parent);
   int current_index = 0;

   //loop through, print each row one-by-one
   for(int i = 1; i <= total_rows; i++) {
      int num_nodes_on_row = pow(2, (i-1));
      int num_spaces = pow(2, (total_rows-i)) - 1;

      //loop through and print each node of the row
      for(int q = 1; q <= num_nodes_on_row; q++) {
         if(q == 1) {
            //special rules for the first node of the row
            //spacer size is half what it SHOULD BE .. the other half
            //falls after the LAST node on the row

            //spacer function simply prints X number of spaces...
            spacer(num_spaces*NODE_WIDTH);
         } else {
            spacer( (num_spaces*NODE_WIDTH) +
                             NODE_WIDTH + (num_spaces*NODE_WIDTH));
         }
         current_index++;
         node* val = seek( parent, current_index,
                                num_nodes_on_row, (num_nodes_on_row*2)-1,
                                1, i);

         if(val == NULL) {
            cout << setw(NODE_WIDTH) << "N";
         } else {
            cout << setw(NODE_WIDTH) << val->data;
         }
      }
      //end of the row, now print newline char
      cout << endl;
   }
</pre>
<p>And there you have it.  You should get something beautiful, like this:</p>
<pre>
              58
      32              73
   7      49      59      79
 4  23   N   N   N   N  73   N
</pre>
<p>Feel free to spend some time getting your code to print lines connecting the nodes.  I added the feature to mine, it looks like this:</p>
<pre>
              70
        _____/  \_____
      55              86
     /  \            /  \
  46      60      74      99
 /  \    /  \    /  \    /  \
26  49   N   N   N   N  98   N
</pre>
<p>Let me know what you think, or if you find bugs in my code!</p>
<p></p>
<p><strong>Edit (08/14/2010):</strong></p>
<hr />
I went back and found the source code.  I'm not sure what happened to my FINAL version.  The one I'm uploading is a little lacking in documentation, but it is at least 5 months old! Yikes.  I tried to clean it up some though.</p>
<p><em><a href="/wp-content/uploads/2010/08/tree.cpp">tree.cpp (12k)</a></em></p>
<hr />
]]></content:encoded>
			<wfw:commentRss>http://seanjordan.me/2010/03/printing-binary-tree-to-stdout-in-c/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Running C/C++ Code as a CGI Script</title>
		<link>http://seanjordan.me/2009/11/running-c-cpp-code-as-a-cgi-script/</link>
		<comments>http://seanjordan.me/2009/11/running-c-cpp-code-as-a-cgi-script/#comments</comments>
		<pubDate>Wed, 25 Nov 2009 08:25:06 +0000</pubDate>
		<dc:creator>Sean Jordan</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://seanjordan.me/?p=129</guid>
		<description><![CDATA[When I first had the realization that this was not only possible, but really simple, I was very excited. Using C/C++ to create dynamic web applications isn&#8217;t new. In fact, C and Perl were originally the primary method for dynamic web based applications. Well, the Internet has been around long enough, that even Perl is [...]]]></description>
			<content:encoded><![CDATA[<p>When I first had the realization that this was not only possible, but really simple, I was very excited.  Using C/C++ to create dynamic web applications isn&#8217;t new.  In fact, C and Perl were originally the primary method for dynamic web based applications.  Well, the Internet has been around long enough, that even Perl is beginning to become obsolete (Thank God).</p>
<p>C++ Web applications are not going to be a game-changer.  If this were true, it would have happened a long time ago.  Will I forget about PHP? Of course not!  Many (probably most) shared hosting solutions won&#8217;t even allow you (with very good reason) to execute arbitrary binary files on their servers.  Mine won&#8217;t.  You also can&#8217;t (to my knowledge) do this technique on Windows servers.  </p>
<p>I WILL, probably, write a few C++ web applications to run on my laptop, just because I&#8217;m a nerd, and the satisfaction I&#8217;d get if from just knowing every time I hit the Home button, I&#8217;m seeing web pages dished up by a C++ script&#8230; I&#8217;ll stop there.</p>
<p>What kind of solutions do I see this as a replacement for PHP (or Ruby, or Python, or ASP, or JSP, or whatever you use)?  </p>
<ul>
<li>You are looking to build a robust web application to be run on your own private web servers.</li>
<p>I&#8217;m thinking, if Twitter was written in C/C++, we wouldn&#8217;t have as many Twitter-outages <img src='http://seanjordan.me/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .  </p>
<li>You are looking to build a high-end distributable web-based software package.</li>
<p>For example, a software package, where the codebase sits on a server, and clients (or internal employees), interface with it through a web browser.  Now we&#8217;re talking APPLICATION, more than just a website.</p>
<li>You are looking to build a web application, and have the ability to run arbitrary binary scripts on your server (such as a private server), and runtime speed is crucial.</li>
<p>With FastCGI and precompiled binary scripts, well-written C/C++ code will trump compile-on-the-fly approaches of PHP, Perl, Python, etc.  (Of course PHP has memcache..)
</ul>
<p>Enough jibber-jabber. Let&#8217;s create a C++ CGI script!  First, you&#8217;ll need to configure Apache to execute CGI scripts.  It&#8217;s general practice (but you may not care.. I don&#8217;t) to create a single directory, and only allow CGI scripts in that directory to be executed.  You&#8217;ve probably seen a lot of cgi-bin/ directories on various websites.  Let&#8217;s say we create a directory at /var/www/cgi.  In this directory, we&#8217;ll put our CGI scripts.  Let&#8217;s tell Apache.</p>
<p>You&#8217;ll want to edit your httpd.conf file (on Ubuntu, it&#8217;s in /etc/apache2).  Add this (as root/sudo):</p>
<pre name="code" class="xml">
&lt;Directory /var/www/cgi&gt;
    Options ExecCGI+
    AddHandler cgi-script .cgi
&lt;/Directory&gt;
</pre>
<p>The <code>Options ExecCGI+</code> line is the one that allows CGI scripts to be executed.  If instead of using a single directory, you opted to make the whole ServerRoot allow CGI scripts (like I did), you&#8217;ll want to make sure the Options aren&#8217;t overridden elsewhere in the server conf.  Namely, check for something in /etc/apache2/sites-available/default (or where ever else your system may store Apache config).  In this file, You may see another <code>&lt;Directory&gt;</code> block for your server root.  Add ExecCGI to the Options list.</p>
<p>You can also create arbitrary file extensions for your CGI scripts with the <code>AddHandler</code> directive.  Imagine the possibilities.</p>
<p>Now, restart Apache.  On Ubuntu:</p>
<p><code>sudo /etc/init.d/apache2 restart</code></p>
<p>When Apache comes back up, you should be ready to roll.  You may feel like throwing in a test Perl script before we get to the C++, just to make sure things are working as expected.  If you aren&#8217;t a Perl Monk (most of us aren&#8217;t), do this:</p>
<p><code>which perl</code></p>
<p>Will tell you where perl is installed (if at all).  It&#8217;s probably /usr/bin/perl.  So then, create this Perl script:</p>
<pre name="code" class="perl">
#!/usr/bin/perl

print qq(Content-type: text/html\n\n);
print qq(Hello, world!);
</pre>
<p>Make sure to chmod that bad boy to at least 755, and hit it in the browser, you should see &#8220;Hello, world!&#8221;.  If not, you probably got one of these:</p>
<ul>
<li>You saw the perl code</li>
<p>   That means the CGI script didn&#8217;t attempt to execute, check back over the steps, make sure you restarted Apache.</p>
<li>You got Forbidden</li>
<p>   You either aren&#8217;t allowed to execute CGI scripts, or didn&#8217;t get the right permissions.</p>
<li>Internal Server Error</li>
<p>   Perl code is probably messed up.  Check out <code>tail /var/logs/apache2/error.log</code> for what SHOULD be a more detailed error message.</p>
<li>File not found</li>
<p>  You probably have a typo in the filename or the address bar <img src='http://seanjordan.me/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .
</ul>
<p>Well, hopefully you have that working now, lets throw down some C++ code.</p>
<p>I&#8217;m not going to teach you C++, so if this code doesn&#8217;t make sense, you should look into learning C++ before approaching this technique (obviously).</p>
<pre name="code" class="c++">

#include &lt;iostream&gt;
#include &lt;cstdlib&gt;

using namespace std;

int main() {

	cout &lt;&lt; "Content-type: text/html\n\n";
	cout &lt;&lt; "Hello World (Wide Web)&lt;br /&gt;" &lt;&lt; endl;

	cout &lt;&lt; getenv("REMOTE_ADDR") &lt;&lt; endl;

}
</pre>
<p>Save this as hello.C, or whatever you want.. and compile the code:</p>
<p><code>g++ -o hello.cgi hello.C</code></p>
<p>Now, make sure that hello.cgi is in /var/www/cgi (or wherever you specified), and hit it in the web browser.  You should see an output something like:</p>
<div class="code-section">
Hello World (Wide Web)<br />
127.0.1.1
</div>
<p>One of the biggest pitfalls I can foresee, is that server-side scripting is not an interactive technique.  Thats why scripting languages are perfect for dynamic web pages.  C++, not being a scripting language by nature may cause you some headaches.  Just be sure to write smart, efficient code.</p>
<p>You can also download a C++ CGI library, to help out with accessing header data, such as Cookies, GET and POST variables, etc. Here is a link to an <a href="http://www.boutell.com/cgic/#obtain">ANSI C library for CGI Programming</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://seanjordan.me/2009/11/running-c-cpp-code-as-a-cgi-script/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
