<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Andy G&#039;s Blog</title>
	<atom:link href="http://gieseanw.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://gieseanw.wordpress.com</link>
	<description>A portfolio of my programming projects</description>
	<lastBuildDate>Wed, 25 Jan 2012 15:16:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='gieseanw.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Andy G&#039;s Blog</title>
		<link>http://gieseanw.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://gieseanw.wordpress.com/osd.xml" title="Andy G&#039;s Blog" />
	<atom:link rel='hub' href='http://gieseanw.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Solving Sudoku, Revisited</title>
		<link>http://gieseanw.wordpress.com/2011/06/16/solving-sudoku-revisited/</link>
		<comments>http://gieseanw.wordpress.com/2011/06/16/solving-sudoku-revisited/#comments</comments>
		<pubDate>Thu, 16 Jun 2011 03:20:52 +0000</pubDate>
		<dc:creator>gieseanw</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Algorithm X]]></category>
		<category><![CDATA[Dancing Links]]></category>
		<category><![CDATA[DLX]]></category>
		<category><![CDATA[Exact Cover]]></category>
		<category><![CDATA[Sodoku Solving]]></category>
		<category><![CDATA[Sudoku]]></category>

		<guid isPermaLink="false">http://gieseanw.wordpress.com/?p=187</guid>
		<description><![CDATA[Thanks to Scott Y’s comments in my article regarding a Sudoku Solver I wrote as part of an AI project, I decided to write a real solver that not only can solve any Sudoku puzzle, but can do it in just a few milliseconds. Long story short: I represented Sudoku as an exact cover problem, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gieseanw.wordpress.com&amp;blog=12012284&amp;post=187&amp;subd=gieseanw&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="text-align:center;"><a href="http://gieseanw.wordpress.com/2011/06/16/solving-sudoku-revisited/"><img class="aligncenter size-full wp-image-28" title="SudokuSolver" src="http://gieseanw.files.wordpress.com/2010/02/sudokusolver.jpg?w=450&#038;h=465" alt="" width="450" height="465" /></a></p>
<p>Thanks to Scott Y’s comments in my <a href="http://gieseanw.wordpress.com/2010/02/13/sudoku-solving-in-a-snap/">article</a> regarding a Sudoku Solver I wrote as part of an AI project, I decided to write a real solver that not only can solve any Sudoku puzzle, but can do it in just a few milliseconds.</p>
<p>Long story short: I represented Sudoku as an exact cover problem, then used Donald Knuth’s Algorithm X and Dancing Links implementation to solve that exact cover problem. Still here? Good, it’s time for me to explain a few things.</p>
<p><span id="more-187"></span></p>
<h2>Exact Cover</h2>
<p>There exists a type of problem called “<a href="http://en.wikipedia.org/wiki/Exact_cover">exact cover</a>”, and while Wikipedia explains things ever so well, I’ll throw in my own explanation that should serve well at least in the context of Sudoku.</p>
<p>Imagine you are challenged to rearrange where you place your cell phone, keys, and wallet. One item must go in a pants pocket, one item must go in a coat pocket, and one item must go in a backpack—and  no two items can be in the same area. Have a solution yet? I hope you said yes. You could solve this a variety of ways: keys in pants, phone in coat, wallet in backpack, etc.</p>
<p>Now imagine you have a hundred pockets, and three hundred different things that must be placed in them in a certain configuration. Now things get a little more difficult. This is because the number of<strong> constraints</strong> has grown much larger, as has the number of items that could potentially satisfy those constraints. How would you go about solving this issue?</p>
<p>Well, an exact cover approach would do the following: create a list of constraints that must be satisfied, then create a list of potential ways to satisfy each constraint. The list of constraints become the column headers of a matrix, and the list of ways to satisfy each constraint become rows in that matrix. To simplify things, let’s consider the original pocket rearrangement problem:</p>
<p>Our list of constraints: pants pocket filled, coat pocket filled, backpack filled</p>
<p>Our list of possible placements of items: keys in pants pocket, keys in coat pocket, keys in backpack, wallet in pants pocket, wallet in coat pocket, wallet in backpack, phone in pants pocket, phone in coat pocket, phone in backpack.</p>
<p>Let’s look at the matrix we made:</p>
<p><a href="http://gieseanw.files.wordpress.com/2011/06/clothes_matrix.jpg"><img class="aligncenter size-full wp-image-195" title="Clothes_Matrix" src="http://gieseanw.files.wordpress.com/2011/06/clothes_matrix.jpg?w=450&#038;h=175" alt="" width="450" height="175" /></a></p>
<p>You’ll notice I labeled the columns (constraints) as questions. The question is whether a row satisfies the constraint. Having Keys in our pants pocket satisfies the constraint that our pants should have an item in them, but not the other two constraints. Let’s look at the matrix with the answers filled in:</p>
<p><a href="http://gieseanw.files.wordpress.com/2011/06/clothes_matrix_answers.jpg"><img class="aligncenter size-full wp-image-196" title="Clothes_Matrix_Answers" src="http://gieseanw.files.wordpress.com/2011/06/clothes_matrix_answers.jpg?w=450&#038;h=175" alt="" width="450" height="175" /></a></p>
<p>In reality, ‘Yes’ and ‘No’ are filled with Boolean True (1) or False (0) values:</p>
<p><a href="http://gieseanw.files.wordpress.com/2011/06/clothes_matrix_answers_boolean.jpg"><img class="aligncenter size-full wp-image-197" title="Clothes_Matrix_Answers_Boolean" src="http://gieseanw.files.wordpress.com/2011/06/clothes_matrix_answers_boolean.jpg?w=450&#038;h=175" alt="" width="450" height="175" /></a></p>
<p>Remember, this matrix represents our constraints, and possibilities that satisfy those constraints; we haven’t solved the problem yet. To solve the problem we have to “exactly cover” the constraint columns. That is, choose a set of rows so that a ‘1’ appears exactly once in each column.</p>
<p>Exact cover problems are typically represented like this: given a matrix of 1’s and 0’s, choose a set of rows so that every column has a ‘1’ in it exactly once.</p>
<p>BUT! We forgot a few constraints on this item rearrangement problem; we can’t exactly place our keys in all three places at once and call it a day, and we definitely need to place each of the three items <em>somewhere</em>. Let’s add a few constraints to reflect these requirements:</p>
<p><a href="http://gieseanw.files.wordpress.com/2011/06/clothes_matrix_more_constraints.jpg"><img class="aligncenter size-full wp-image-198" title="Clothes_Matrix_More_Constraints" src="http://gieseanw.files.wordpress.com/2011/06/clothes_matrix_more_constraints.jpg?w=450&#038;h=117" alt="" width="450" height="117" /></a></p>
<p>The initial solution I wrote down (pants: keys, coat: phone, backpack: wallet) does exactly cover our matrix, but we did this without even thinking, so how can we tell a computer to do it?</p>
<h2>Algorithm X</h2>
<p>There are a few ways to go about solving this exact cover problem; the simplest (naive) way would be to just randomly pick a set of 3 rows over and over again until a solution is found. We can be a little smarter than that though.</p>
<p>The famous Donald Knuth is credited with formulating an algorithm to solve this exact cover problem, an algorithm he dubbed “<a href="http://en.wikipedia.org/wiki/Algorithm_X">Algorithm X</a>”. Again, while the Wikipedia page is incredibly helpful, I’ll offer my own interpretation using the above example matrix.</p>
<p>Returning to the items-in-pockets problem, when we selected keys to go in the pants pocket, we also disregarded the wallet or phone being in that pocket because of the rule that no two items could be in the same area. That is, the rows compete against each other to be part of the solution, and when one row is chosen, its competition is removed. We also disregarded the keys being in any of the other pockets, so other rows where the key gets placed get removed too.</p>
<p>Algorithm X functions on this exact premise: select a constraint to fulfill, try to add an entry into the solution, remove competing entries, then repeat on the remaining matrix until a solution is found or a solution is impossible to find.</p>
<p>Let’s run Algorithm X on our simple problem:</p>
<p>Step 0: The matrix is not empty, so continue</p>
<p>Step 1: Choose a constraint to fulfill (arbitrarily choose Pants Pocket)</p>
<p>Step 2: Choose a row that fulfills that constraint (Keys in pants) and add to solution</p>
<p>Step 3: For each constraint that row satisfies, remove any other rows that also satisfy that constraint (Wallet in Pants, Phone in Pants, Keys in Coat, Keys in Backpack), and remove the fulfilled constraints’ columns (Pants Pocket and Keys Placed)<br />
<a href="http://gieseanw.files.wordpress.com/2011/06/algorithmxstep1.png"><img class="aligncenter size-full wp-image-200" title="AlgorithmXStep1" src="http://gieseanw.files.wordpress.com/2011/06/algorithmxstep1.png?w=450&#038;h=117" alt="" width="450" height="117" /></a>-&gt;</p>
<p><a href="http://gieseanw.files.wordpress.com/2011/06/algorithmxstep1_2.png"><img class="aligncenter size-full wp-image-201" title="AlgorithmXStep1_2" src="http://gieseanw.files.wordpress.com/2011/06/algorithmxstep1_2.png?w=450&#038;h=123" alt="" width="450" height="123" /></a></p>
<p>Step 4: The matrix is not empty, so continue</p>
<p>Step 5: Choose a remaining constraint to fulfill (Coat Pocket)</p>
<p>Step 6: Choose a row that fulfills that constraint (Wallet in coat) and add to solution</p>
<p>Step 7: For each constraint that row satisfies, remove any other rows that also satisfy that constraint (Wallet in Backpack, Phone in coat), and remove the fulfilled constraints’ columns (Coat Pocket and Wallet Placed)</p>
<p><a href="http://gieseanw.files.wordpress.com/2011/06/algorithmxstep2_1.png"><img class="aligncenter size-full wp-image-202" title="AlgorithmXStep2_1" src="http://gieseanw.files.wordpress.com/2011/06/algorithmxstep2_1.png?w=450&#038;h=137" alt="" width="450" height="137" /></a></p>
<p>-&gt;<a href="http://gieseanw.files.wordpress.com/2011/06/algorithmxstep2_2.png"><img class="aligncenter size-full wp-image-203" title="AlgorithmXStep2_2" src="http://gieseanw.files.wordpress.com/2011/06/algorithmxstep2_2.png?w=450" alt=""   /></a></p>
<p>Step 8: The matrix is not empty, so continue</p>
<p>Step 9: Choose a remaining constraint to fulfill (Backpack)</p>
<p>Step 10: Choose a row that fulfills that constraint (Phone in backpack) and add to solution</p>
<p>Step 11: For each constraint that row satisfies, remove any other rows that also satisfy that constraint (None), and remove the fulfilled constraints’ columns (Backpack and Phone Placed)</p>
<p><a href="http://gieseanw.files.wordpress.com/2011/06/algorithmxstep3_1.png"><img class="aligncenter size-full wp-image-204" title="AlgorithmXStep3_1" src="http://gieseanw.files.wordpress.com/2011/06/algorithmxstep3_1.png?w=450" alt=""   /></a>-&gt;</p>
<p><a href="http://gieseanw.files.wordpress.com/2011/06/algorithmxstep3_2.png"><img class="aligncenter size-full wp-image-205" title="AlgorithmXStep3_2" src="http://gieseanw.files.wordpress.com/2011/06/algorithmxstep3_2.png?w=450" alt=""   /></a></p>
<p>Step 12: The matrix is empty! We’ve found a solution!</p>
<p>Now that you have a basic understanding of Algorithm X, think about the same problem except you are given that your phone is already in your pants pocket. You perform the same competition-removal, and now your matrix is smaller and easier to manage. This is what Sudoku is like.</p>
<h2>Making Sudoku an Exact Cover Problem</h2>
<p>Sudoku, like organizing your pockets, can be represented as an exact cover problem. Our matrix will just be a lot bigger.</p>
<p>Sudoku has a few explicit rules: Values 1-9 must be in every Row, Column, and Box; and the numbers may not repeat in any Row, Column, or Box. An implicit rule is that every cell must contain a value.</p>
<p>Using the almighty power of algebra, we can discern that there are 324 constraints. Every row must have 9 values in it, and there are 9 rows (9 * 9 = 81), every column must have 9 values in it, and there are 9 columns (9 *9 = 81), every box must have 9 values in it, and there are 9 boxes (9 * 9=81), and every cell must have a value in it, and there are 81 cells.  81 + 81 + 81 + 81 = 324.</p>
<p>Again, we can use algebra to discover that there will be 729 rows in our matrix, because there are 729 row, column, value triplets (boxes are ignored because box value is a function of row and column values). Row, column, and value triplets represent a single entry into the empty Sudoku puzzle: (row 1, column 1, value 1), ( row 1, column 1, value 2), … , (row 9, column 9, value 9). There are 9 rows, 9 columns, and 9 values in a Sudoku puzzle: 9 * 9 *9 = 729 rows in our exact cover matrix.</p>
<p>Each of these rows also satisfies four constraints: a row-value pair, a column-value pair, a row-column pair, and a box-value pair. That is, (row 1, column 1, value 1) satisfies the constraint that row 1 must have the value of 1 in it somewhere, column 1 must have the value of 1 in it somewhere, row 1 column 1 must have a value in it, and box 1 must have the value of 1 in it somewhere.</p>
<p>A sample Sudoku exact cover matrix can be seen <a href="http://www.stolaf.edu/people/hansonr/sudoku/exactcovermatrix.htm">here</a>. Although, not an entirely accurate matrix, it should give you an example of the representation. My own complete matrix is included near the end of this article with the source code of my program.</p>
<p>Now that we’ve turned Sudoku into an exact cover problem, we’re ready to run our Algorithm X on it.</p>
<h2>Dancing Links (DLX)</h2>
<p>The Sudoku’s exact cover matrix is a little larger than our clothes-items one. Also, it has <em>way</em> more 0’s than 1’s in it. This type of matrix is called a <a href="http://en.wikipedia.org/wiki/Sparse_matrix">sparse matrix</a>, and if we simply stored the whole thing in a 324 x 729 array, we’d spend an inordinate amount of time searching for 1’s.</p>
<p>So our old friend Donald Knuth created <a href="http://en.wikipedia.org/wiki/Dancing_Links">Dancing Links</a>, or DLX. The gist of DLX is that we represent our matrix as a quadruply-linked circular list that only stores the 1’s from our matrix.</p>
<p>Each node in our list has links to the nodes to its right, left, top, and bottom areas in the matrix. It also points to a special column header node.</p>
<p>The graphic below (found at <a href="http://www.ocf.berkeley.edu/~jchu/publicportal/sudoku/sudoku.paper.html">here</a>) depicts what our data structure looks like, though it doesn’t show that there is a link between <em>every</em> node and its column header.</p>
<p><a href="http://gieseanw.files.wordpress.com/2011/06/dancing_links.png"><img class="aligncenter size-full wp-image-207" title="Dancing_Links" src="http://gieseanw.files.wordpress.com/2011/06/dancing_links.png?w=450&#038;h=420" alt="" width="450" height="420" /></a></p>
<p>This circular linked list not only removes the task of searching through 0s to find 1s, but is also very efficient for performing removal and re-instatement of nodes because of the simple logic that removing a node from a row simply requires:</p>
<p>Node-&gt;left-&gt;right = Node-&gt;right;</p>
<p>Node-&gt;right-&gt;left = Node-&gt;left;</p>
<p>And reinstating the node requires</p>
<p>Node-&gt;left-&gt;right = Node;</p>
<p>Node-&gt;right-&gt;left = Node;</p>
<p>Using DLX with Algorithm X is a very fast way to solve any Sudoku puzzle.</p>
<p><strong>The Implementation</strong></p>
<p>My implementation is written in C++ on Visual Studio 2008 running on Windows XP. If you ever use this source code, all I ask is that you credit me for it (you don&#8217;t even need a link to this article). I used .doc files because they were the only real file upload option WordPress would give me outside of .docx, and I figure more people will find compatibility with .doc files. If you can&#8217;t manage to download and view these files then e-mail me at my email address found on my About Me page.</p>
<p><strong>SudokuMatrix</strong></p>
<p><a href="http://gieseanw.files.wordpress.com/2011/06/sudokumatrix_h.doc">SudokuMatrix_H</a></p>
<p><a href="http://gieseanw.files.wordpress.com/2011/06/sudokumatrix_cpp.doc">SudokuMatrix_CPP</a></p>
<p>These files are the heart of the program – they implement the dancing links and algorithm x functionality. Puzzles are fed to the program via simple text files at the moment, but feel free to build a GUI around them!</p>
<p><strong>Definitions</strong></p>
<p><a href="http://gieseanw.files.wordpress.com/2011/06/definitions_h.doc">definitions_H</a></p>
<p>This file controls sizing information about the matrix. My solver works in the general case, not just standard 9&#215;9 Sudoku Puzzles.  Commented out in the file is the ability to expand the solver to 10&#215;10, 12&#215;12, or 16&#215;16, though you may need to allow your program to use more memory!</p>
<p><strong>Driver</strong></p>
<p><a href="http://gieseanw.files.wordpress.com/2011/06/driver_cpp.doc">driver_cpp</a></p>
<p>This file simply instantiates and uses a SudokuMatrix, looping to allow the user to solve multiple puzzles per session.</p>
<p><strong>Exact Cover Matrix</strong></p>
<p><a href="http://gieseanw.files.wordpress.com/2011/06/covermatrix.doc">covermatrix</a></p>
<p>This file is simply the binary output of my 324 x 729 exact cover matrix for a 9&#215;9 Sudoku. There’s no row or column headers, though I very heavily document the assumptions I make about it in SudokuMatrix.h</p>
<h2>Closing Thoughts</h2>
<p>Algorithm X’s little secret is that it’s actually a brute force solver—it doesn’t always choose the next best candidate to be part of the solution. In that regard, every iteration of the algorithm is a guess! It’s just a very, very fast brute-force solver: I was able to solve expert level 16&#215;16 Sudokus in under a second!</p>
<p>Algorithm X is a great candidate to implement <a href="http://en.wikipedia.org/wiki/Recursion">recursively</a>: the same manipulations are performed on an object until one of two base cases are met, and if the failure base case is encountered, the algorithm can easily backtrack by simply returning one level up from the recursive stack.</p>
<p>The hardest thing for me to get my mind around was the cover() and uncover() functions that hide and reinstate values into the matrix. At first this was because I misinterpreted how it should’ve worked and accidentally covered the columns of ALL values that were covered. Then I didn’t realize that the uncover function must work in the opposite order that the cover function did.</p>
<p>I had a lot of help using <a href="http://cgi.cse.unsw.edu.au/~xche635/dlx_sodoku/">this site</a> as a reference aside from the Wikipedia articles.</p>
<p>I’m not too sure how long this program took me to write… maybe 20 hours or so. Most of that was spent debugging the cover() and uncover() functions, though! I’m sure you could do it in half the time or less.</p>
<p>I’m all ears for questions or comments; I’ve done the best I could to thoroughly explain the concepts at work here. The source code is available above this section, in case you skipped here to the end.</p>
<br /> Tagged: <a href='http://gieseanw.wordpress.com/tag/algorithm-x/'>Algorithm X</a>, <a href='http://gieseanw.wordpress.com/tag/dancing-links/'>Dancing Links</a>, <a href='http://gieseanw.wordpress.com/tag/dlx/'>DLX</a>, <a href='http://gieseanw.wordpress.com/tag/exact-cover/'>Exact Cover</a>, <a href='http://gieseanw.wordpress.com/tag/sodoku-solving/'>Sodoku Solving</a>, <a href='http://gieseanw.wordpress.com/tag/sudoku/'>Sudoku</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gieseanw.wordpress.com/187/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gieseanw.wordpress.com/187/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gieseanw.wordpress.com/187/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gieseanw.wordpress.com/187/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gieseanw.wordpress.com/187/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gieseanw.wordpress.com/187/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gieseanw.wordpress.com/187/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gieseanw.wordpress.com/187/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gieseanw.wordpress.com/187/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gieseanw.wordpress.com/187/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gieseanw.wordpress.com/187/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gieseanw.wordpress.com/187/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gieseanw.wordpress.com/187/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gieseanw.wordpress.com/187/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gieseanw.wordpress.com&amp;blog=12012284&amp;post=187&amp;subd=gieseanw&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gieseanw.wordpress.com/2011/06/16/solving-sudoku-revisited/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/7496124d499d578df1e3a6ff85e7ae03?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gieseanw</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/02/sudokusolver.jpg" medium="image">
			<media:title type="html">SudokuSolver</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2011/06/clothes_matrix.jpg" medium="image">
			<media:title type="html">Clothes_Matrix</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2011/06/clothes_matrix_answers.jpg" medium="image">
			<media:title type="html">Clothes_Matrix_Answers</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2011/06/clothes_matrix_answers_boolean.jpg" medium="image">
			<media:title type="html">Clothes_Matrix_Answers_Boolean</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2011/06/clothes_matrix_more_constraints.jpg" medium="image">
			<media:title type="html">Clothes_Matrix_More_Constraints</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2011/06/algorithmxstep1.png" medium="image">
			<media:title type="html">AlgorithmXStep1</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2011/06/algorithmxstep1_2.png" medium="image">
			<media:title type="html">AlgorithmXStep1_2</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2011/06/algorithmxstep2_1.png" medium="image">
			<media:title type="html">AlgorithmXStep2_1</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2011/06/algorithmxstep2_2.png" medium="image">
			<media:title type="html">AlgorithmXStep2_2</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2011/06/algorithmxstep3_1.png" medium="image">
			<media:title type="html">AlgorithmXStep3_1</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2011/06/algorithmxstep3_2.png" medium="image">
			<media:title type="html">AlgorithmXStep3_2</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2011/06/dancing_links.png" medium="image">
			<media:title type="html">Dancing_Links</media:title>
		</media:content>
	</item>
		<item>
		<title>Think You’re Good At Mario?</title>
		<link>http://gieseanw.wordpress.com/2011/03/10/think-you%e2%80%99re-good-at-mario/</link>
		<comments>http://gieseanw.wordpress.com/2011/03/10/think-you%e2%80%99re-good-at-mario/#comments</comments>
		<pubDate>Thu, 10 Mar 2011 00:41:17 +0000</pubDate>
		<dc:creator>gieseanw</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[A star]]></category>
		<category><![CDATA[A*]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[Artificial Intelligence]]></category>
		<category><![CDATA[Infinite Mario Bros.]]></category>
		<category><![CDATA[Mario]]></category>
		<category><![CDATA[Mario bot]]></category>

		<guid isPermaLink="false">http://gieseanw.wordpress.com/?p=171</guid>
		<description><![CDATA[Update: I will be presenting the results of this research at MAICS 2011 as well as UD&#8217;s Stander Symposium 2011! In August 2009, Sergey Karakovskiy and Julian Togelius held a competition on behalf of the ICE-GIC (IEEE Consumer Electronics Society Games Innovation Conference) for contestants to build a soft-bot that played Super Mario. The Super [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gieseanw.wordpress.com&amp;blog=12012284&amp;post=171&amp;subd=gieseanw&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<span style="text-align:center; display: block;"><a href="http://gieseanw.wordpress.com/2011/03/10/think-you%e2%80%99re-good-at-mario/"><img src="http://img.youtube.com/vi/XU1_zNwyHWA/2.jpg" alt="" /></a></span>
<p><strong>Update: </strong>I will be presenting the results of this research at <a href="http://maics2011.ewu.edu/index.php/MAICS2011">MAICS 2011</a> as well as UD&#8217;s <a href="http://stander.udayton.edu/">Stander Symposium 2011</a>!</p>
<p>In August 2009, Sergey Karakovskiy and Julian Togelius held a <a href="http://julian.togelius.com/mariocompetition2009/">competition</a> on behalf of the ICE-GIC (IEEE Consumer Electronics Society Games Innovation Conference) for contestants to build a soft-bot that played Super Mario.</p>
<p>The Super Mario Engine they used was a modified version of one built in Java by the one and only Markus Persson , a.k.a. “Notch” of Minecraft fame. The Engine is named Infinite Mario Bros., and is still playable online for free. Entrants into the competition had to build an agent who would tell the engine Mario’s next move every 40 milliseconds.</p>
<p>The competition was held in 2009, and again in 2010. <a href="http://www.doc.ic.ac.uk/~rb1006/projects:marioai">Robin Baumgarten</a> won this competition with his bot, AStarAgent, both years. I stumbled upon this competition in late August 2010 and was immediately intrigued. I had wanted to build an agent that played a known game –any game, really—for some time. A modern first person shooter like Halo or RTS like Starcraft would be mind-blowing, exciting, and most of all, recognizable to family and friends.</p>
<p><span id="more-171"></span></p>
<p>(Warning, this is a very long article!)</p>
<p>Fortunately I was starting some research as an undergrad at the University of Dayton, but was lukewarm on my current idea – building a LEGO Mindstorm bot to find its way through a maze using genetic algorithms. Here, with Mario, I saw a bigger and better opportunity. I was going to build a Mario bot that was better than the best one, and do it with a Genetic Algorithm.</p>
<h2>Genetic Algorithms</h2>
<p>What is a <a href="http://en.wikipedia.org/wiki/Genetic_Algorithm">Genetic Algorithm</a>? Well, the entire field of Evolutionary Computation is relatively new, even for the field of Computer Science. Essentially Evolutionary Computation attempts to replicate, in software, portions of the biological phenomenon of evolution. If complex intelligent beings like Humans evolved out of some random primordial goop, then why couldn’t an adequate and capable program evolve out of some random operators?</p>
<p>The subset of Evolutionary Computation known as Genetic Algorithms or GA’s are, in their simplest forms, just evolution in code. Automated trial-and-error if you will. Start with a random population of chromosomes, use natural selection to choose the best ones, mate, produce children, have mutations in children DNA, use natural selection to choose the best children, rinse and repeat. That is virtually the entire logic behind a Genetic Algorithm, and it’s not extraordinarily difficult to implement in code, either.</p>
<p>The hard part is this thing we’re calling “natural selection”. In the real world, it’s obvious; if you can’t survive, your genes don’t get passed on to the next generation, you are “selected out”.  In code it can be a little different. A programmer needs to discover a method for testing a member of the population to determine that member’s fitness level, and what makes a member “fit” isn’t always abundantly clear. Sure, if you’re trying to write a GA to evolve an organism to walk, then you can objectively say “If organism A is able to walk farther than organism B, organism A is more fit”. But it’s not always that easy. For example, if you were writing a GA to evolve a population of notes in various keys to create pleasant music, first you need to be able to define what “pleasant” music is. How do you write code that says “Yup, this music is pleasant.” Or “Nope, this music is discordant”?</p>
<p>Luckily for me (and Mario), one fitness function stands out: If Mario A can travel further in a level than Mario B, then Mario A is better.  Of course, my eventual fitness function is slightly more complex, and on top of it, this type of fitness complicates things.</p>
<p>Mankind’s history of evolution goes back billions of years, through billions of generations of organisms. If I want to write a GA that runs even 100,000 generations, each generation should be evaluated pretty quickly, right? If one generation takes 2 full seconds to evaluate, then just 100K evaluations will take me just over 2 days. If my fitness function for Mario is directly related to how far the bot can travel in its world, we’ve got some issues.</p>
<p>First off, Mario’s world may be appear simple to us, but it’s way more complex than something like a Sliding Tiles game. The bot needs to think as much as it can during those 40 milliseconds. Since Mario can move forward, backwards, duck, jump, optionally “go faster”, and do many of these things on combination, he has more than a handful of possible moves he can choose to do at any one time. Plus, he needs to account for Koopa’s, Piranha Plants, and bottomless pits to top it off. How can a bot possibly make an intelligent decision given all these variables?</p>
<p>Robin’s bot used a sort of <a href="http://en.wikipedia.org/wiki/A_star">A*</a> search, hence the name AStarAgent, so that seemed like a pretty good starting point. Lucky for me, I showed up to the Mario party late, and the competition had already run. This means that the source code for all the bots had been released, and I could actually go dissect Robin’s bot to see what made him tick, and how I think I could improve it.</p>
<p>By Robin’s own admission, his bot was hastily put together, and written for speed, not elegance. And it showed. After spending weeks pouring through his code slowly figuring out what everything meant and how it all worked together I threw Robin’s entire A* search out. Yup, sometimes you’re better off working with something you understand as if you had written (because you DID write it!).</p>
<p>I didn’t throw everything out, however. What I think made Robin’s bot better than other similar ones was the accuracy of his agent’s internal representation of the world.</p>
<h2>A* Searches</h2>
<p><a href="http://gieseanw.files.wordpress.com/2011/03/astarsearch.jpg"><img class="aligncenter size-full wp-image-176" title="AStarSearch" src="http://gieseanw.files.wordpress.com/2011/03/astarsearch.jpg?w=450" alt=""   /></a></p>
<p>Some Mario bots were neural nets that spewed out decisions based on the matrix of input, some used hand-written algorithms specific to Mario, but the better ones kept an internal representation and ran some sort of search on the information available to discover the best move available.</p>
<p>Boiled down to its basics, an <a href="http://en.wikipedia.org/wiki/A_star">A* search</a> works as follows:</p>
<ul>
<li>Start with some sort of starting state (the root of a tree, or in this case, Mario’s current location).</li>
<li>Generate all possible children states from the starting state, evaluate them, and place them on a list (the OPEN list).</li>
<li>Take the best child from the OPEN list, and generate its possible children states. Evaluate those children, and place them on the OPEN list, too.</li>
<li>Continue removing the best child from the OPEN list until you find a solution, run out of time, or you have exhausted all possibilities (no solution).</li>
</ul>
<p>An implementation is a little more complex than that, but you get the idea. The hardest part about writing an A* search, just like for our GA, is this function that evaluates how “good” a state is. In a GA we’d call the function the fitness function. In the A* search we’ll call it the Static Evaluation Function (SEF).</p>
<p>So Robin’s bot used an A* search with a SEF function that favored states where Mario was not injured, and he had the most potential to move forward. Essentially, states that were farther right and moving faster on the screen were favorable so long as Mario wasn’t taking damage.</p>
<h3>The SEF</h3>
<p>Well, crud, that’s a pretty good static evaluation function, in theory at least. Robin had placed some arbitrary, no doubt empirical weights on values of speed, position, and health. The first improvement I saw, outside of rewriting his code to run smoother, was to improve these weights. But why stop there?</p>
<p>In Mario, oftentimes if you can stay really high in the air, then you don’t have to worry about enemies or holes in the ground. What if Mario should be valuing a mix of vertical and horizontal positions? What if Mario should make an effort to grab a koopa troopa’s shell so that he can release it later to remove enemies in his path? What if Mario allowed himself to take some damage so long as he didn’t die and it made him move faster through the level? These are all good thoughts, but how do I weight these things against each other? It seemed Robin had discovered his weights through trial and error. Not only did I not want to spend the time running through trial and error myself, but with the possible combinations of all the weights I was thinking of, it could take years! Thus the motivation to automate it.</p>
<p>I said before that you could think of GA’s as automated trial and error, and that’s exactly what I needed. When I rewrote Robin’s A* algorithm, I needed to discover a better SEF, and what better way to do this than through evolution? Before I continue, I should probably make it abundantly clear exactly how this works:</p>
<ol>
<li>Mario receives a percept of his surroundings from the game engine</li>
<li>Mario decides on his next course of action, and tells the engine his next action</li>
<li>The engine steps forward, and gives Mario a new percept.</li>
<li>Repeat until Mario dies or finishes the level.</li>
</ol>
<p>In step 2, when Mario is deciding his next course of action, he is running an A* search, using his SEF to tell him which states are good and which are not. A Genetic Algorithm to evolve the SEF complicates things, turning the sequence into this:</p>
<ol>
<li>GA gets the next SEF from a population of SEFs waiting to be tested, and inserts the SEF into the Mario bot.</li>
<li>GA tests the Mario bot (steps 1-4 above)</li>
<li>GA places this evaluated SEF on the OPEN list</li>
</ol>
<p>So you can see that the GA encompasses the game. Since the fitness of each SEF depends on how well it causes Mario to play a level, testing just one SEF will be tedious. That is, just one generation of five SEFs causes a bot to run through a level 5 times. Tedious and time consuming, right?</p>
<p>Right. If this is the route I was going to take (and I was), I needed to make sure that the evaluation of each Mario bot took as little time as possible. A normal length level could take more than 20 seconds to complete if the bot performed flawlessly, and if the bot simply stood still, then one evaluation would be over a minute long. Let’s see, 40 seconds per evaluation, 5 bots per generation, 10,000 generations, comes to… just over 23 days. Better computing power wasn’t going to help me here, I needed to make sure that I had a short, yet challenging test level, and a small time limit. Eventually I got down to a level that an optimal bot could complete in about 13 seconds. Running just 800 generations with a time limit capped at 25 seconds, the simulation ran for roughly 24 hours.</p>
<h2>The Results</h2>
<p>And the results were… interesting. There were roughly 3 types of bots: bots that didn’t get anywhere, bots that made it to some random point near the middle, and bots that finished fairly quickly. A typical distribution, right? Well yeah, except when you consider that this was the case for just about every generation, and doesn’t reflect the entire evolution. That is, some bots in the very first few generations showed this kind of distribution (which could be expected, since they start randomly), but some bots in the last few generations also show this kind of distribution.</p>
<p>Why is that? Well, I’ve decided it has to do with how I structured my genetic algorithm. In general, you want a genetic algorithm to converge to one or a few solutions, and rarely perform worse (I can’t say never, because random mutations can always result in an unfit member). I, however, did not write my program to converge so much as to explore more possible bots, given that I only had 800 generations to do it.</p>
<p>One way to perform the “mating” stage of a genetic algorithm is to allow every member in the population a chance to be chosen as a parent. However, these chances are weighted against each member’s score compared to the entire population. If the total population score is 100, and a member has a score of 10, that member has a 10% chance of being chosen. Likewise, a member with a score of 1 has a 1% chance to be chosen.</p>
<p>What I did was disallow identical members with identical scores in my population. That is, if an identical static evaluation function as one already in my population was created, and evaluated to the same score as the one in the population had, it was thrown out. Since more fit SEFs are chosen more often, I foresaw that more and more identical SEFs with high scores would be introduced to the population, and the GA would quickly converge, which is normal, but I favored more searching over convergence.</p>
<p>A future version of this program will be run on a Beowulf cluster to take advantage of parallel computing. In this way, I can evaluate multiple SEFs simultaneously instead of sequentially. Additionally, some tweaks to the GA algorithm itself (like allowing identical members in my population) will be had in the future.</p>
<p>After the first run of the GA, I ended up with some fairly well-performing bots. But they still weren’t better than Robin Baumgarten’s. I couldn’t accept defeat, so I made another, longer level, took the top 5 bots from the first GA, and used them as the starting population for round two. This time I only ran for 320 generations, as the level was nearly 3 times as long as the first one, and the execution took almost 50 hours!</p>
<p>The results from this run were impressive. The program finally evolved a bot or two that could best Robin’s on a few levels. Some manual tweaking later, and I have a bot that always performs as good or better than Robin’s!</p>
<p>This video at the top of the article is my bot running through a fairly lengthy level. The biggest difference between my bot and Robin’s is that my bot will gladly sacrifice some damage just to beat the level a little faster.</p>
<p>As this article is running on a little long, I’ll cut it off here. If you read this far, good for you! If there’s enough interest, I’ll post a follow up article on any aspect of the Mario bot I didn’t cover here (of which there are many). I’m glad to answer any questions as well. Since you got this far, here is a funny picture:</p>
<p><a href="http://gieseanw.files.wordpress.com/2011/03/dance_lessons.jpg"><img class="aligncenter size-full wp-image-174" title="dance_lessons" src="http://gieseanw.files.wordpress.com/2011/03/dance_lessons.jpg?w=450&#038;h=462" alt="" width="450" height="462" /></a></p>
<br /> Tagged: <a href='http://gieseanw.wordpress.com/tag/a-star/'>A star</a>, <a href='http://gieseanw.wordpress.com/tag/a/'>A*</a>, <a href='http://gieseanw.wordpress.com/tag/ai/'>AI</a>, <a href='http://gieseanw.wordpress.com/tag/artificial-intelligence/'>Artificial Intelligence</a>, <a href='http://gieseanw.wordpress.com/tag/infinite-mario-bros/'>Infinite Mario Bros.</a>, <a href='http://gieseanw.wordpress.com/tag/mario/'>Mario</a>, <a href='http://gieseanw.wordpress.com/tag/mario-bot/'>Mario bot</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gieseanw.wordpress.com/171/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gieseanw.wordpress.com/171/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gieseanw.wordpress.com/171/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gieseanw.wordpress.com/171/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gieseanw.wordpress.com/171/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gieseanw.wordpress.com/171/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gieseanw.wordpress.com/171/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gieseanw.wordpress.com/171/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gieseanw.wordpress.com/171/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gieseanw.wordpress.com/171/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gieseanw.wordpress.com/171/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gieseanw.wordpress.com/171/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gieseanw.wordpress.com/171/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gieseanw.wordpress.com/171/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gieseanw.wordpress.com&amp;blog=12012284&amp;post=171&amp;subd=gieseanw&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gieseanw.wordpress.com/2011/03/10/think-you%e2%80%99re-good-at-mario/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/7496124d499d578df1e3a6ff85e7ae03?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gieseanw</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2011/03/astarsearch.jpg" medium="image">
			<media:title type="html">AStarSearch</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2011/03/dance_lessons.jpg" medium="image">
			<media:title type="html">dance_lessons</media:title>
		</media:content>
	</item>
		<item>
		<title>Using Profile Information on a Base Page in ASP.NET</title>
		<link>http://gieseanw.wordpress.com/2010/12/08/using-profile-information-on-a-base-page-in-asp-net/</link>
		<comments>http://gieseanw.wordpress.com/2010/12/08/using-profile-information-on-a-base-page-in-asp-net/#comments</comments>
		<pubDate>Wed, 08 Dec 2010 05:16:40 +0000</pubDate>
		<dc:creator>gieseanw</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Base Page]]></category>
		<category><![CDATA[Profile]]></category>
		<category><![CDATA[System.Configuration.SettingsPropertyNotFoundExceptio]]></category>

		<guid isPermaLink="false">http://gieseanw.wordpress.com/?p=153</guid>
		<description><![CDATA[Recently I was attempting to code a base page in an ASP.NET project because I decided it would make future upkeep easy, and it was good practice to learn. What I wanted to do actually was set a page’s theme based on an entry in their profile, PreferredTheme. The thing is, I kept getting slammed [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gieseanw.wordpress.com&amp;blog=12012284&amp;post=153&amp;subd=gieseanw&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="text-align:center;"><a href="http://gieseanw.files.wordpress.com/2010/12/asp-profile-banner.png"><img class="aligncenter size-full wp-image-161" title="ASP Profile Banner" src="http://gieseanw.files.wordpress.com/2010/12/asp-profile-banner.png?w=450" alt=""   /></a></p>
<p>Recently I was attempting to code a base page in an ASP.NET project because I decided it would make future upkeep easy, and it was good practice to learn. What I wanted to do actually was set a page’s theme based on an entry in their profile, PreferredTheme. The thing is, I kept getting slammed by System.Configuration.SettingsPropertyNotFoundException errors and for the life of me couldn’t find much good information on the web. After piecing together things here and there, I’ve figured it out and thought I’d share it here in case somebody else has the same problem.</p>
<p><span id="more-153"></span></p>
<p>The simplest profile setting in a web.config file would look something like this:</p>
<p><a href="http://gieseanw.files.wordpress.com/2010/12/asp-profile.jpg"><img class="aligncenter size-full wp-image-155" title="ASP profile" src="http://gieseanw.files.wordpress.com/2010/12/asp-profile.jpg?w=450" alt=""   /></a></p>
<p>Note: only authenticated users can have this profile information. If you want anonymous users to be provided profiles, use the allowAnonymous option in the profile property, and set anonymousIdentification enabled to “true”.</p>
<p>What I was trying to do in my base page was simply set the Page.Theme property in the Page_PreInit method like so:</p>
<div id="attachment_156" class="wp-caption aligncenter" style="width: 457px"><a href="http://gieseanw.files.wordpress.com/2010/12/page_preinit_1sttry.jpg"><img class="size-full wp-image-156" title="Page_PreInit_1stTry" src="http://gieseanw.files.wordpress.com/2010/12/page_preinit_1sttry.jpg?w=450" alt=""   /></a><p class="wp-caption-text">Click to Enlarge</p></div>
<p>But that doesn’t even compile, so I followed some leads from Google around and found <a href="http://forums.asp.net/p/1312307/2591137.aspx">this page</a> telling me to actually use the ProfileCommon() class to create a new instance of ProfileCommon, and then use the GetUserProfile() method to get the authenticated user’s profile, then finally get the information I needed out of the profile. Sounds great, right? Wrong! It may have compiled, but it sure didn’t run! I kept getting the SettingsPropertyNotFoundException, and I couldn’t quite pinpoint why.</p>
<p>Well, according to <a href="http://msdn.microsoft.com/en-us/library/2y3fs9xs.aspx">MSDN</a>,</p>
<blockquote><p>“When your application runs, ASP.NET creates a ProfileCommon class, which is a dynamically generated class that inherits the <a href="http://msdn.microsoft.com/en-us/library/system.web.profile.profilebase.aspx">ProfileBase</a> class. The dynamic ProfileCommon class includes properties created from the profile property definitions you specify in your application configuration. An instance of this dynamic ProfileCommon class is then set as the value of the <a href="http://msdn.microsoft.com/en-us/library/system.web.httpcontext.profile.aspx">Profile</a> property of the current <a href="http://msdn.microsoft.com/en-us/library/system.web.httpcontext.aspx">HttpContext</a> and is available to pages in your application.”</p></blockquote>
<p>After some thought (and a little help from a <a href="http://stackoverflow.com/questions/963746/profile-getprofile-on-base-class">StackOverfow answer</a> suggesting I go through the HttpContext to get Profile), I think figured out what was happening.</p>
<p>The dynamically created ProfileCommon class seems to be standing in for the authenticated user’s Profile information, so when I try calling Profile.PreferredTheme, I get that error because PreferredTheme simply doesn’t exist in our dynamic class. Instead, the more proper way is how the kind soul at SO stated: HttpContext.Current.Profile, which properly points to the authenticated user’s profile information.</p>
<p>After a little modification of this bit of code, I ended up with this new Page_PreInit function, which works just dandy:</p>
<div id="attachment_157" class="wp-caption aligncenter" style="width: 460px"><a href="http://gieseanw.files.wordpress.com/2010/12/page_preinit_2ndtry.jpg"><img class="size-full wp-image-157" title="Page_PreInit_2ndTry" src="http://gieseanw.files.wordpress.com/2010/12/page_preinit_2ndtry.jpg?w=450&#038;h=103" alt="" width="450" height="103" /></a><p class="wp-caption-text">Click to Enlarge</p></div>
<p>So there you have it: how to properly get Profile information from an authenticated user from your Base Page in ASP.NET. I hope this helps somebody out there.</p>
<br /> Tagged: <a href='http://gieseanw.wordpress.com/tag/asp-net/'>ASP.NET</a>, <a href='http://gieseanw.wordpress.com/tag/base-page/'>Base Page</a>, <a href='http://gieseanw.wordpress.com/tag/profile/'>Profile</a>, <a href='http://gieseanw.wordpress.com/tag/system-configuration-settingspropertynotfoundexceptio/'>System.Configuration.SettingsPropertyNotFoundExceptio</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gieseanw.wordpress.com/153/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gieseanw.wordpress.com/153/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gieseanw.wordpress.com/153/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gieseanw.wordpress.com/153/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gieseanw.wordpress.com/153/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gieseanw.wordpress.com/153/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gieseanw.wordpress.com/153/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gieseanw.wordpress.com/153/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gieseanw.wordpress.com/153/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gieseanw.wordpress.com/153/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gieseanw.wordpress.com/153/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gieseanw.wordpress.com/153/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gieseanw.wordpress.com/153/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gieseanw.wordpress.com/153/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gieseanw.wordpress.com&amp;blog=12012284&amp;post=153&amp;subd=gieseanw&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gieseanw.wordpress.com/2010/12/08/using-profile-information-on-a-base-page-in-asp-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/7496124d499d578df1e3a6ff85e7ae03?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gieseanw</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/12/asp-profile-banner.png" medium="image">
			<media:title type="html">ASP Profile Banner</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/12/asp-profile.jpg" medium="image">
			<media:title type="html">ASP profile</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/12/page_preinit_1sttry.jpg" medium="image">
			<media:title type="html">Page_PreInit_1stTry</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/12/page_preinit_2ndtry.jpg" medium="image">
			<media:title type="html">Page_PreInit_2ndTry</media:title>
		</media:content>
	</item>
		<item>
		<title>Why You Should Embrace the Principle of Locality</title>
		<link>http://gieseanw.wordpress.com/2010/11/22/why-you-should-embrace-the-principle-of-locality/</link>
		<comments>http://gieseanw.wordpress.com/2010/11/22/why-you-should-embrace-the-principle-of-locality/#comments</comments>
		<pubDate>Mon, 22 Nov 2010 01:11:54 +0000</pubDate>
		<dc:creator>gieseanw</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Compression]]></category>
		<category><![CDATA[Locality]]></category>
		<category><![CDATA[Web Crawling]]></category>
		<category><![CDATA[Web Mining]]></category>

		<guid isPermaLink="false">http://gieseanw.wordpress.com/?p=140</guid>
		<description><![CDATA[The principle of locality states that in computer systems, data that has been used recently will likely be used again soon, or if a particular location in memory was needed recently, it will likely be referenced again soon. In more general terms, we could state the principle of locality as “What has happened recently will [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gieseanw.wordpress.com&amp;blog=12012284&amp;post=140&amp;subd=gieseanw&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://gieseanw.files.wordpress.com/2010/11/penguins_locality.jpg"><img class="aligncenter size-full wp-image-142" title="Penguins_Locality" src="http://gieseanw.files.wordpress.com/2010/11/penguins_locality.jpg?w=450&#038;h=310" alt="" width="450" height="310" /></a></p>
<p>The principle of locality states that in computer systems, data that has been used recently will likely be used again soon, or if a particular location in memory was needed recently, it will likely be referenced again soon. In more general terms, we could state the principle of locality as “What has happened recently will likely happen again.”</p>
<p>But how does this help you?</p>
<p><span id="more-140"></span></p>
<p>Well, for one, if you recently used a program like Google Chrome (and exited), your operating system might use this to assume that you’ll use it again and keep some properties about that program in cache so that the program can be quickly loaded again. Go ahead and try it yourself. Open up a program you haven’t used in some time that typically takes a little while to open. Then close the program. Then reopen it. Did the program load noticeably faster the second time?</p>
<p>In one of my classes recently we were discussing principles a web crawler might use when the topic of locality came up. The professor stated that, when building an inverted index for a search engine, we could exploit the principle of locality.</p>
<p>What does that mean? Here’s a brief primer on web crawling and search engines. If you’re already familiar with all this, simply skip to the section starting at “When my professor stated”</p>
<p>When you type a query into a search engine (like “United States” or something), what is the search engine doing? A simplistic engine will go through a database of documents it had a crawler previously crawl and scrape the text from. For all the terms in the database, an <a href="http://en.wikipedia.org/wiki/Inverted_index">inverted index</a> can be built. Think of an inverted index as the Glossary in the back of your textbook. For each term, you get a list of pages the term appears on. A normal (non-inverted) index would say “For each page, give a list of all the terms”. An inverted index makes much more sense to have, right?</p>
<p>For each term in your query, the inverted index can be searched to find pages that the term appears in. Each entry into the simple inverted index looks like this:</p>
<p><a href="http://gieseanw.files.wordpress.com/2010/11/inverted_index_entry.jpg"><img class="aligncenter size-full wp-image-143" title="Inverted_Index_Entry" src="http://gieseanw.files.wordpress.com/2010/11/inverted_index_entry.jpg?w=450&#038;h=37" alt="" width="450" height="37" /></a></p>
<p>With &#8220;United States&#8221;, something like this:</p>
<p><a href="http://gieseanw.files.wordpress.com/2010/11/inverted_index_us.jpg"><img class="aligncenter size-full wp-image-144" title="Inverted_Index_US" src="http://gieseanw.files.wordpress.com/2010/11/inverted_index_us.jpg?w=450&#038;h=43" alt="" width="450" height="43" /></a></p>
<p>The Document ID’s are simply what number the search engine’s crawler has assigned a particular page during its crawl.</p>
<p>As you can imagine, storing these lists quickly balloons into a huge memory consumer. Any techniques on data compression are welcomed. One of those is called Gap notation using delta encoding.</p>
<p>When my professor stated that we could use the principle of locality, she was referring to this technique of gap notation with delta encoding. Instead of storing document IDs as 1, 2, 4, 10, 12, 15, 18, 27, etc. we could instead just store the gaps between document IDs. Our list then becomes 1, 1, 2, 6, 2, 3, 3, 9.</p>
<p>To store these IDs in memory we could take one of two approaches: a fixed size variable or a variable of dynamic size. There are a couple problems of using a fixed size variable. To do so requires an assumption of the maximum amount of space needed. If this assumption is too small, then we’ll encounter a gap larger than what we can store in memory, and if the assumption is too large, then we’ve wasted space instead of saved it during our compression!</p>
<p>Therefore, it is a good idea to use variable-width storage. This is what delta encoding does; it allows us to store our gap numbers in a dynamic fashion. Delta encoding requires that we store the gap as a combination of a unary number and a binary number, called a gamma code.</p>
<p>A unary number can be thought of as “ticks” that one might use to count quantities of something. So 3 units of a widget looks like three tick marks: I I I. In unary, the number 3 would appear like this: 110. The 0 is a “stop-bit” indicating the end of the count.</p>
<p>The first half (unary) of the gamma code is equivalent to floor(log<sub>2</sub> X) + 1. X is the gap between IDs. The floor function rounds any decimal result down to the nearest integer, so floor(log<sub>2</sub> 9) = 3 just like floor(log<sub>2</sub> (8)) = 3. If our gap number was 9, then the first half of our gamma code becomes floor(log<sub>2</sub> 9) +1 = 4 (decimal) = 1110 (unary). The second half of the gamma code is equivalent to X – 2 <sup>(floor (log<sub>2</sub> x))</sup> where X is the gap width. This equation will guarantee that the largest result is X/2 and the smallest is 0.  The gap size will never be 0 because documents have unique IDs.</p>
<p>If our gap number is X, then the second half of the gamma code (binary) is 9 – 2 <sup>(floor(log<sub>2</sub> (9)))</sup> = 9 – 2<sup>3</sup> = 9 – 8 = 1 (decimal) = 001 (binary). As you can see, I represented the binary number with a few trailing 0s. Why? Calculating the first half of the code also determines the number of bits we’ll use to represent the second half. That is, floor(log<sub>2</sub> X) will be the number of bits we use to represent the second half of the code. As floor(log<sub>2</sub> (9)) = 3, we’ll only use three bits to represent the second half of the gamma code – 001.</p>
<p>Our total number of a gap size of 9 is then 1110001. This is a 7 bit number! If the actual document IDs were 1 and 10. Then we just used 7 bits to encode document ID 10, when it could have easily been represented as 1010, a four bit number! If every gap size was 9, we’d actually be using extra space to be storing all of our gaps!</p>
<p>But hang on for a minute. Consider the number of documents that a term could point to in an inverted index for, say, Google? A million would be a conservative estimate, and indeed searching “United States” turns up about 1.8 billion pages. What if the document IDs with gap sizes of 9 were actually 128 and 137? Using delta encoding we find a gamma code of 1110001, a 7 bit number, but not using any encoding at all to represent 137 we get 10001001, an 8-bit number! We just saved 1 bit of memory! If every gap size was of 9 or less, then we’d save at minimum about a billion bits for a term like United States, or about 125 megabytes. Over even just a few thousand different terms, storage savings add up fast.</p>
<p>But how can we be sure that these gap sizes are going to result in memory savings? Or: How does the principle of locality work to save memory? That the exact question that popped into my head during the lecture, and I couldn’t help but figure it out for myself, hence this post. According to the principle of locality in a spatial sense, document IDs are going to cluster around related words. Think about NASA’s website. Every page will likely have something in common with any other page, like Space or stars.  Therefore the gap size in pages for a term like “astronaut” is likely to be small. With semantic locality, we make the assumption that terms will be clustered according to their semantic meanings. Then our gap sizes for document ids of pages within the same websites is very small, with the larger gaps made between web sites, and there are far fewer web sites than there are pages in web sites.</p>
<p>For a small web, our memory savings will be insignificant, if any, but for humongous sets of data that require entire data warehouses to store, using the principal of locality applied with delta encoding results in less memory required and cost savings for you and your business.</p>
<br /> Tagged: <a href='http://gieseanw.wordpress.com/tag/compression/'>Compression</a>, <a href='http://gieseanw.wordpress.com/tag/locality/'>Locality</a>, <a href='http://gieseanw.wordpress.com/tag/web-crawling/'>Web Crawling</a>, <a href='http://gieseanw.wordpress.com/tag/web-mining/'>Web Mining</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gieseanw.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gieseanw.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gieseanw.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gieseanw.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gieseanw.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gieseanw.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gieseanw.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gieseanw.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gieseanw.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gieseanw.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gieseanw.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gieseanw.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gieseanw.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gieseanw.wordpress.com/140/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gieseanw.wordpress.com&amp;blog=12012284&amp;post=140&amp;subd=gieseanw&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gieseanw.wordpress.com/2010/11/22/why-you-should-embrace-the-principle-of-locality/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/7496124d499d578df1e3a6ff85e7ae03?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gieseanw</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/11/penguins_locality.jpg" medium="image">
			<media:title type="html">Penguins_Locality</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/11/inverted_index_entry.jpg" medium="image">
			<media:title type="html">Inverted_Index_Entry</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/11/inverted_index_us.jpg" medium="image">
			<media:title type="html">Inverted_Index_US</media:title>
		</media:content>
	</item>
		<item>
		<title>Discount Stack Overflows</title>
		<link>http://gieseanw.wordpress.com/2010/07/20/discount-stack-overflows/</link>
		<comments>http://gieseanw.wordpress.com/2010/07/20/discount-stack-overflows/#comments</comments>
		<pubDate>Tue, 20 Jul 2010 00:08:47 +0000</pubDate>
		<dc:creator>gieseanw</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://gieseanw.wordpress.com/?p=135</guid>
		<description><![CDATA[If you&#8217;re sick of paying through the nose at your local Wal-Mart or Best Buy on ways to overflow your stack, you could be saving hundreds by just doing it yourself! While working on a recent project I accidentally made a very rookie mistake when creating a recursively called Depth First Search function that resulted [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gieseanw.wordpress.com&amp;blog=12012284&amp;post=135&amp;subd=gieseanw&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://gieseanw.files.wordpress.com/2010/07/infinitemirror.jpg"><img class="aligncenter size-full wp-image-137" title="infiniteMirror" src="http://gieseanw.files.wordpress.com/2010/07/infinitemirror.jpg?w=450&#038;h=311" alt="" width="450" height="311" /></a><br />
If you&#8217;re sick of paying through the nose at your local Wal-Mart or Best Buy on ways to overflow your stack, you could be saving hundreds by just doing it yourself! While working on a recent project I accidentally made a very rookie mistake when creating a recursively called <a href="http://en.wikipedia.org/wiki/Depth-first_search">Depth First Search</a> function that resulted in overflowing the stack from too many function calls.</p>
<p><span id="more-135"></span>What I did was essentially this:</p>
<p>bool recursiveFunction(Graph* g, node* next)</p>
<p>{</p>
<p style="padding-left:30px;">//base case 1</p>
<p style="padding-left:30px;">return false;</p>
<p style="padding-left:30px;">//base case 2</p>
<p style="padding-left:30px;">return true;</p>
<p style="padding-left:30px;">//recursive case</p>
<p style="padding-left:30px;">return (recursiveFunction(g,next-&gt;neighbor1) ||         recursiveFunction(g,next-&gt;neighbor2);</p>
<p>}</p>
<p>What I <span style="text-decoration:underline;">wasn&#8217;t</span> doing was checking a neighbor node to see if I had searched it first before moving onto the other cases. So basically the call stack looked like this:</p>
<p>recursiveFunction(g, Node1);<br />
recursiveFunction(g, Node2);<br />
recursiveFunction(g, Node1);<br />
recursiveFunction(g, Node2);<br />
&#8230;<br />
recursiveFunction(g,Node1);</p>
<p>and on and on as two neighboring Nodes continually check each other without any indication that they should be. My mistake isn&#8217;t restricted to just DFS on a graph, but really any sort of graph search. A tree is not so big of a deal because nodes typically do not search their parents and thus the search is always &#8220;down&#8221; the tree, so our problem is really restricted to graphs.</p>
<p>So the challenge becomes designing your system to easily check to see whether a node in your graph has been searched before, and there are a million ways to do it, from adding a reference to the node in a container of searched nodes to building a &#8216;searched&#8217; boolean into your node structure that can be flipped, although this will require more time.</p>
<p>This is a lighthearted, easy fix for most programmers, but just goes to show once again that the Design stage of software creation is just as important as the Implement one; although we can all agree the Implement stage is infinitely more fun to do <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gieseanw.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gieseanw.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gieseanw.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gieseanw.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gieseanw.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gieseanw.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gieseanw.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gieseanw.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gieseanw.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gieseanw.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gieseanw.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gieseanw.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gieseanw.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gieseanw.wordpress.com/135/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gieseanw.wordpress.com&amp;blog=12012284&amp;post=135&amp;subd=gieseanw&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gieseanw.wordpress.com/2010/07/20/discount-stack-overflows/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/7496124d499d578df1e3a6ff85e7ae03?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gieseanw</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/07/infinitemirror.jpg" medium="image">
			<media:title type="html">infiniteMirror</media:title>
		</media:content>
	</item>
		<item>
		<title>A Robot to Solve Rubik&#8217;s Cube</title>
		<link>http://gieseanw.wordpress.com/2010/05/03/a-robot-to-solve-rubiks-cube/</link>
		<comments>http://gieseanw.wordpress.com/2010/05/03/a-robot-to-solve-rubiks-cube/#comments</comments>
		<pubDate>Mon, 03 May 2010 05:03:08 +0000</pubDate>
		<dc:creator>gieseanw</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[Robots]]></category>

		<guid isPermaLink="false">http://gieseanw.wordpress.com/?p=129</guid>
		<description><![CDATA[&#160; For a fun little final project in my AI course, the class was split into teams that were to take a Lego Mindstorms NXT 2.0 robot kit and build a creative robot to do&#8230;something! Really, it was a cool way to finish a really interesting course. There were robots that could walk to a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gieseanw.wordpress.com&amp;blog=12012284&amp;post=129&amp;subd=gieseanw&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>&nbsp;</p>
<p style="text-align:center;"><a href="http://gieseanw.files.wordpress.com/2010/05/cubesolver.jpg"><img class="size-full wp-image-130 aligncenter" title="CubeSolver" src="http://gieseanw.files.wordpress.com/2010/05/cubesolver.jpg?w=450" alt=""   /></a></p>
<p>For a fun little final project in my AI course, the class was split into teams that were to take a Lego Mindstorms NXT 2.0 robot kit and build a creative robot to do&#8230;something! Really, it was a cool way to finish a really interesting course. There were robots that could walk to a bucket and sort colored balls, one to traverse a maze, one that transforms from a rover into a walker&#8230;. and ours, which solves <a href="http://www.rubiks.com/">Rubik&#8217;s Cubes</a>.</p>
<p><span id="more-129"></span>As part of the final project, we had to create a website with some information about the robot, <a href="http://sites.google.com/site/cps481cubesolver/">here&#8217;s ours</a>. Here is the abstract taken from the site:</p>
<p style="padding-left:30px;"><span style="color:#444444;"><span style="color:#444444;">Our robot is officially named the &#8220;One Armed Wonder&#8221;, and was invented by Daniele Benedettelli and described in his book LEGO MINDSTORMS NXT Thinking Robots . The architecture consists of an arm that can flip the cube over, or hold it in place while the platform underneath turns the bottom layer of the cube. A webcam is mounted on the unit, and it as well as the lego brick are plugged into a laptop with the cubesolver software installed. We will demo it by first putting the cube on the platform (randomized of course), and starting the cubesolver program which should automatically scan the cube in, generate a solution, then execute the solution. However, the webcam and software sometimes do not cooperate so the program is very likely to read in some colors wrong. If this scenario occurs we will be able to manually make corrections on the spot, and allow the robot to continue. The robot takes about 2 minutes to finish executing the necessary moves to solve the puzzle.</span></span></p>
<p><span style="color:#444444;"><span style="color:#444444;">And here&#8217;s a video of it in action:</span></span></p>
<p><span style="color:#444444;"><span style="color:#444444;"><span style="text-align:center; display: block;"><a href="http://gieseanw.wordpress.com/2010/05/03/a-robot-to-solve-rubiks-cube/"><img src="http://img.youtube.com/vi/5RIfgUVYRE4/2.jpg" alt="" /></a></span><br />
</span></span></p>
<p><span style="color:#444444;"><span style="color:#444444;">As you can see, sometimes the bot had some trouble turning the Cube. The Cube was a well-used hand-me-down that was a bit stiff. We loosened it a bit with some WD40, but it got almost too loose such that it would overturn. We had to help it turn a few times by hand.<br />
</span></span></p>
<br /> Tagged: <a href='http://gieseanw.wordpress.com/tag/ai/'>AI</a>, <a href='http://gieseanw.wordpress.com/tag/robots/'>Robots</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gieseanw.wordpress.com/129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gieseanw.wordpress.com/129/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gieseanw.wordpress.com/129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gieseanw.wordpress.com/129/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gieseanw.wordpress.com/129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gieseanw.wordpress.com/129/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gieseanw.wordpress.com/129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gieseanw.wordpress.com/129/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gieseanw.wordpress.com/129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gieseanw.wordpress.com/129/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gieseanw.wordpress.com/129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gieseanw.wordpress.com/129/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gieseanw.wordpress.com/129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gieseanw.wordpress.com/129/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gieseanw.wordpress.com&amp;blog=12012284&amp;post=129&amp;subd=gieseanw&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gieseanw.wordpress.com/2010/05/03/a-robot-to-solve-rubiks-cube/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/7496124d499d578df1e3a6ff85e7ae03?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gieseanw</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/05/cubesolver.jpg" medium="image">
			<media:title type="html">CubeSolver</media:title>
		</media:content>
	</item>
		<item>
		<title>What&#8217;s Wrong With This Code?</title>
		<link>http://gieseanw.wordpress.com/2010/03/29/whats-wrong-with-this-code/</link>
		<comments>http://gieseanw.wordpress.com/2010/03/29/whats-wrong-with-this-code/#comments</comments>
		<pubDate>Mon, 29 Mar 2010 21:44:58 +0000</pubDate>
		<dc:creator>gieseanw</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[C/C++]]></category>

		<guid isPermaLink="false">http://gieseanw.wordpress.com/?p=118</guid>
		<description><![CDATA[I meant to include this in my post about Building a DNS Resolver, as it is a small, yet significant bug that took me a little while to find. What the code should be doing, is reading a string from a file (where all strings in the file are guaranteed to be 255 characters or [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gieseanw.wordpress.com&amp;blog=12012284&amp;post=118&amp;subd=gieseanw&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://gieseanw.files.wordpress.com/2010/03/wrongstring.jpg"><a href="http://gieseanw.files.wordpress.com/2010/03/rightstring1.jpg"><br />
</a></a><a href="http://gieseanw.files.wordpress.com/2010/03/wrongstring1.jpg"><img class="aligncenter size-full wp-image-124" title="wrongString" src="http://gieseanw.files.wordpress.com/2010/03/wrongstring1.jpg?w=450" alt=""   /></a>I meant to include this in my post about <a href="http://gieseanw.wordpress.com/2010/03/25/building-a-dns-resolver/">Building a DNS Resolver</a>, as it is a small, yet significant bug that took me a little while to find. What the code <em>should</em> be doing, is reading a string from a file (where all strings in the file are guaranteed to be 255 characters or less), then pushing that string into a Queue. So before you jump to the whole article, can you see what&#8217;s wrong with the code?</p>
<p><span id="more-118"></span>What tipped me off was that, after reading in a bunch of IP addresses, I would grab the first one, parse it using strtok, do whatever with that, then grab the next string, parse it, etc.</p>
<p>The thing is, whenever I would grab the second string, instead of being something like 127.0.0.1 it would be 126, which was invalid. The third string would also be 126, as well as the fourth, fifth, etc.</p>
<p>Initially I thought the problem was with my parsing, then the problem was with how I grabbed the next string from the Queue. Eventually I traced it back to this bit of code; where I was reading and inserting each item into the Queue. Then I had one of those *slaps his forehead* moments where I couldn&#8217;t believe I had made such a simple mistake. Figured it out yet?</p>
<p>The code instantiates a pointer to a string, allocates memory, then reads that string in. Then it inserts the POINTER into a Queue. Each subsequent iteration overwrites the data held in the memory the pointer points to, and the same address is constantly inserted into the Queue. Therefore a change on one item of data changes the entire Queue of items.</p>
<p>The first string I would read in would be something like 126.0.0.5, which is then tokenized by periods, leaving the pointer to finally point to only 126. Thing is, as that changed the whole container, every subsequent IP was invalid.</p>
<p>Here&#8217;s the really simple fix to the code:</p>
<p><a href="http://gieseanw.files.wordpress.com/2010/03/rightstring.jpg"><a href="http://gieseanw.files.wordpress.com/2010/03/rightstring2.jpg"><img class="aligncenter size-full wp-image-126" title="rightString" src="http://gieseanw.files.wordpress.com/2010/03/rightstring2.jpg?w=450" alt=""   /></a><br />
</a>Just allocating new memory for the pointer on each iteration will ensure the pointer points to separate memory addresses each time it is inserted into the Queue. Therefore, new string won&#8217;t overwrite old ones, and you don&#8217;t have to worry about accidentally ruining the whole container at once!</p>
<br /> Tagged: <a href='http://gieseanw.wordpress.com/tag/cc/'>C/C++</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gieseanw.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gieseanw.wordpress.com/118/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gieseanw.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gieseanw.wordpress.com/118/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gieseanw.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gieseanw.wordpress.com/118/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gieseanw.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gieseanw.wordpress.com/118/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gieseanw.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gieseanw.wordpress.com/118/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gieseanw.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gieseanw.wordpress.com/118/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gieseanw.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gieseanw.wordpress.com/118/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gieseanw.wordpress.com&amp;blog=12012284&amp;post=118&amp;subd=gieseanw&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gieseanw.wordpress.com/2010/03/29/whats-wrong-with-this-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/7496124d499d578df1e3a6ff85e7ae03?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gieseanw</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/03/wrongstring1.jpg" medium="image">
			<media:title type="html">wrongString</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/03/rightstring2.jpg" medium="image">
			<media:title type="html">rightString</media:title>
		</media:content>
	</item>
		<item>
		<title>ASCII Hangman</title>
		<link>http://gieseanw.wordpress.com/2010/03/29/ascii-hangman/</link>
		<comments>http://gieseanw.wordpress.com/2010/03/29/ascii-hangman/#comments</comments>
		<pubDate>Mon, 29 Mar 2010 20:37:52 +0000</pubDate>
		<dc:creator>gieseanw</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[games]]></category>

		<guid isPermaLink="false">http://gieseanw.wordpress.com/?p=95</guid>
		<description><![CDATA[Back in late 2007 I was fresh out of my freshman year of a computer science degree, and thought I knew C++ well enough to build another game. The &#8220;Haunted House&#8221; game took forever to build and was full of bugs at first, but that was a full semester of classes ago. Now I was [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gieseanw.wordpress.com&amp;blog=12012284&amp;post=95&amp;subd=gieseanw&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://gieseanw.files.wordpress.com/2010/03/hangman_banner.jpg"><img class="aligncenter size-full wp-image-96" title="Hangman_Banner" src="http://gieseanw.files.wordpress.com/2010/03/hangman_banner.jpg?w=450&#038;h=212" alt="" width="450" height="212" /></a>Back in late 2007 I was fresh out of my freshman year of a computer science degree, and thought I knew C++ well enough to build another game. <a href="http://gieseanw.wordpress.com/2010/02/14/a-text-based-game/">The &#8220;Haunted House&#8221; game</a> took forever to build and was full of bugs at first, but that was a full <em>semester</em> of classes ago. Now I was ready to make another game, also I was bored and wanted to stay sharp, so I built an ASCII-art Hangman game.</p>
<p><span id="more-95"></span>Thank God I was so thorough in my commenting at the time, because going back through my code in 2007 would have been much difficult if I hadn&#8217;t been taught from the start to comment properly. Here&#8217;s some notes at the top of my driver file:</p>
<blockquote><p>Types of things being practiced:<br />
Parsing strings for proper input<br />
Parsing strings for numbers<br />
Using and modifying files<br />
Using linked sorted/unsorted lists<br />
Using linked sorted/unsorted lists that are templated<br />
Using linked sorted/unsorted lists containing other linked lists<br />
Creating ADTs<br />
Clean navigation between game modes<br />
Random drawing<br />
Preventing same item to be drawn randomly twice<br />
User generated content</p></blockquote>
<p>As seems to be a theme in my projects, I am really afraid of string parsing, and for that reason seem to practice it constantly. Again, as noted in the Haunted House piece, I still had no idea the STL even existed! So I had data structures like templated sorted linked lists built entirely by my own hands. Sheesh!</p>
<p>If you examine the banner image carefully, you&#8217;ll see that the user is given 1 of 6 menu choices upon game start: Play Game (versus Computer), Play Game vs Human, Add New Word (to the dictionary), Help, and Quit. I&#8217;ll start from the top.</p>
<p>I used a string to gather all user input to avoid the system crashing when given a string when prompted for a number. I thought it worth noting that I was unfamiliar with the <a href="http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/">atoi()</a> function at the time, and manually parsed numerical values from my strings (which, if my memory serves me right, was not too easy).</p>
<p>At game start, a variety of information is loaded from text files. The &#8220;Categories&#8221; text file lists names of other text files that contain words related to certain categories. I never really got around to loading a wealth of categories, so my test data consisted of &#8220;Movies&#8221;, &#8220;People&#8221;, &#8220;Words&#8221; with about 5 words in each accompanying text file. When the user wishes to play, the game randomly selects a category, then randomly selects a word from that category and &#8220;anonymizes&#8221; it to show to the user. Thus, a word like &#8220;Brobdingnagian&#8221; becomes &#8220;_ _ _ _ _ _ _ _ _ _ _ _ _ _ &#8220;:</p>
<p><a href="http://gieseanw.files.wordpress.com/2010/03/hangman_gamestart1.jpg"><img class="aligncenter size-medium wp-image-99" title="Hangman_GameStart" src="http://gieseanw.files.wordpress.com/2010/03/hangman_gamestart1.jpg?w=300&#038;h=269" alt="" width="300" height="269" /></a>As you can see, in the top of the screen I track Lives, Score, and the # of misses the player has left before they lose another life. After a letter is guessed, it is listed to the player so they don&#8217;t make repeat guesses (even though a repeat guess does not hurt them). This is where I started approaching the game with a design philosophy, what game designers call &#8220;Pen and Paper&#8221; design, where you flesh something out on paper before writing a line of code.</p>
<p>Here&#8217;s my initial design:</p>
<p><a href="http://gieseanw.files.wordpress.com/2010/03/hangman_design_notes1.jpg"><img class="aligncenter size-medium wp-image-100" title="Hangman_Design_Notes1" src="http://gieseanw.files.wordpress.com/2010/03/hangman_design_notes1.jpg?w=222&#038;h=300" alt="" width="222" height="300" /></a><img class="aligncenter size-medium wp-image-101" title="Hangman_Design_Notes2" src="http://gieseanw.files.wordpress.com/2010/03/hangman_design_notes2.jpg?w=128&#038;h=300" alt="" width="128" height="300" /></p>
<p>Pretty simple, right? I had, at least defined a definite order of game progression, the # of tries a player would get, and that I would want to track how many guesses a player has left so they wouldn&#8217;t need to wonder whether the little stick guy is wearing shoes or not.</p>
<p>As the player progresses through the game, they accumulate points for finishing words. When they get a word right, a new category and word are loaded, with the system favoring words that have not yet been seen by the player.</p>
<p>When they choose to quit, the system checks a high scores list it loaded in at game start to see if the player has a new high score. If so, they are informed as much and prompted to enter their name in. Old high scores are bumped off the list to make room.</p>
<p><a href="http://gieseanw.files.wordpress.com/2010/03/hangman_highscore.jpg"><img class="aligncenter size-medium wp-image-102" title="Hangman_Highscore" src="http://gieseanw.files.wordpress.com/2010/03/hangman_highscore.jpg?w=300&#038;h=95" alt="" width="300" height="95" /></a>Something I learned very early through my <a href="http://measuring-satisfaction.com/2009/04/07/tips-for-better-survey-design-1-hallway-testing/">Hallway Testing</a> was that people, including myself want to type stuff like &#8220;I, John Doe, am the greatest Hangman player evar!!! <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> &#8221; into the high score. Heck, if you give someone free reign to type something, they&#8217;ll type crap like that no matter what. So, I had to clean the text. I partially used the string cleaning functions I had in place for the Hangman project, removing numbers and non-character symbols. I just had to limit the player input this time around. See how the game just took the &#8220;Andy&#8221; part of &#8220;Andy G&#8217;s Blog&#8221;? This is a small, yet significant detail in design, in my opinion.</p>
<p>Okay, jumping out of order while I&#8217;m on the topic of High Scores. I had the idea from the start to have some sort of continuing state from game to game, so I came up with the whole idea to track scores and write them to a text file to be loaded in at next game start. This way people could brag about being the best Hangman player to have played my game. So, after pressing &#8217;3&#8242; at game menu, they see this:</p>
<p><a href="http://gieseanw.files.wordpress.com/2010/03/hangman_highscore_list.jpg"><img class="aligncenter size-medium wp-image-103" title="Hangman_Highscore_list" src="http://gieseanw.files.wordpress.com/2010/03/hangman_highscore_list.jpg?w=300&#038;h=134" alt="" width="300" height="134" /></a>Reliably inserting into and deleting from a sorted linked list created by hand was problematic for me at first, so it was actually a little while later before I ironed out all the bugs in the highscores functionality. Therefore, only my test scores and my roommate Kyle are represented in the table today. Another shout out to Kyle for being a patient tester for every game I&#8217;ve made to this point.</p>
<p>The linked list that tracks highscores is A) Sorted by score and B) only permitted to be 7 entries long. So after a new name is inserted, the last entry must be chopped off. As a newbie dealing with pointers, this inevitably led to some invalid pointer reference issues.</p>
<p>It was easy to implement because I had fleshed out exactly how scores and the leaderboard should work during my pen and paper design sessions. Here&#8217;s my design notes exactly as I wrote them three years ago:</p>
<p><a href="http://gieseanw.files.wordpress.com/2010/03/hangman_design_notes3.jpg"><img class="aligncenter size-medium wp-image-105" title="Hangman_Design_Notes3" src="http://gieseanw.files.wordpress.com/2010/03/hangman_design_notes3.jpg?w=300&#038;h=136" alt="" width="300" height="136" /></a>(click to enlarge)</p>
<p>So now I get to tell you about the two most exciting parts of the project: First, a 2-player game, and second: editing the existing dictionary to add new words and categories.</p>
<p>First, Versus Play!</p>
<p><a href="http://gieseanw.files.wordpress.com/2010/03/hangman_vs_play.jpg"><img class="aligncenter size-full wp-image-106" title="Hangman_Vs_Play" src="http://gieseanw.files.wordpress.com/2010/03/hangman_vs_play.jpg?w=450&#038;h=144" alt="" width="450" height="144" /></a>I always, always made sure I would ask the user if their input was right before I would accept it. Because there&#8217;s always a pretty good chance a fast typer hits enter just as he/she realizes they made a mistake. One simple redundancy check for accurate input ensures that the user doesn&#8217;t have to quit out of versus mode and get back in just to get the word or category right (which would disrupt gameplay and not be very fun).</p>
<p>I sort of blacklisted all symbols that weren&#8217;t letters from the words to make anonymizing and displaying them easier for myself, but if I went back and did it today, the punctuation would stay in, and just not be anonymized. andy gs blog makes less sense than Andy G&#8217;s Blog.</p>
<p>Anyway, I digress. In this mode one player gets to enter a category, then a word for that category, and the system does the rest&#8230; Player one just needs to make sure Player two isn&#8217;t looking at the screen or something while they enter in the word!</p>
<p>After a valid word has been entered, player two plays the game exactly as if they were playing single player mode. If they get it right, player two wins. Looking back at my old code, I literally copy-pasted the code from playing a normal game into playing a versus game. Ach! Nowadays that code, or most of it, would get thrown in its own function to be used by both modes! I think at the time, I was on the cusp of understanding this, but didn&#8217;t quite make it.</p>
<p><a href="http://gieseanw.files.wordpress.com/2010/03/hangman_vs_play2.jpg"><img class="aligncenter size-full wp-image-107" title="Hangman_Vs_Play2" src="http://gieseanw.files.wordpress.com/2010/03/hangman_vs_play2.jpg?w=450" alt=""   /></a></p>
<p>Instead, the copied code was modified a bit so that the player had no score, still 6 guesses, and only 1 life. It looks great, and it&#8217;s easy to transition into if one was familiar with single player-mode, but there is some code waste there that could have been solved by a simple function that took a mode variable as a parameter.</p>
<p>Next comes the final point I wanted to practice at the time: User-generated content. Initially I wanted to have the entire dictionary editable, a player could insert, update, and delete. Instead, the problem seemed too difficult for me at the time, so I settled on just allowing the player to create a new word under a current category, or create a new category with a new word. Indeed, the insert, update, delete part doesn&#8217;t sound all that hard today, but back then I just had a little trouble trying to get how I could do it all into my head:</p>
<p><a href="http://gieseanw.files.wordpress.com/2010/03/hangman_usercontent.jpg"><img class="aligncenter size-full wp-image-108" title="Hangman_UserContent" src="http://gieseanw.files.wordpress.com/2010/03/hangman_usercontent.jpg?w=450" alt=""   /></a>It was cool to see my new content added to the game dynamically:</p>
<p><a href="http://gieseanw.files.wordpress.com/2010/03/hangman_usercontent2.jpg"><img class="aligncenter size-full wp-image-110" title="Hangman_UserContent2" src="http://gieseanw.files.wordpress.com/2010/03/hangman_usercontent2.jpg?w=450&#038;h=125" alt="" width="450" height="125" /></a>After this, the user was told to enter in a new word, like so:</p>
<p><a href="http://gieseanw.files.wordpress.com/2010/03/hangman_newword.jpg"><img class="aligncenter size-full wp-image-112" title="Hangman_NewWord" src="http://gieseanw.files.wordpress.com/2010/03/hangman_newword.jpg?w=450" alt=""   /></a>Now, I thought about listing out all words in alphabetical order for the person adding words, but at the time rethought to myself that a person could just do that and look at all the existing words to cheat. But this is a bit of a contradiction, right? If you&#8217;re giving someone administrative privileges to add words and categories, they should also be able to view and delete existing words and categories!</p>
<p>I ensured that duplicate words couldn&#8217;t be entered:</p>
<p><a href="http://gieseanw.files.wordpress.com/2010/03/hangman_newwordfail.jpg"><img class="aligncenter size-full wp-image-113" title="Hangman_NewWordFail" src="http://gieseanw.files.wordpress.com/2010/03/hangman_newwordfail.jpg?w=450" alt=""   /></a>So that&#8217;s the gist of the program! Or at least as much as I remember about it. In retrospect it sounds like a conglomeration of a handful of easy concepts that came together to make a really cool project!</p>
<p>Still, I can&#8217;t say I was the BEST with pointers or dynamically allocated memory, as there persists a memory leak in the program, who knows, perhaps I&#8217;ll sift through the code and fix it!</p>
<p>I&#8217;m ready and willing to provide all the source code and/or executable to anyone who is interested. Just contact me at my e-mail address listed on my &#8220;About Me&#8221; page.</p>
<br /> Tagged: <a href='http://gieseanw.wordpress.com/tag/games/'>games</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gieseanw.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gieseanw.wordpress.com/95/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gieseanw.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gieseanw.wordpress.com/95/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gieseanw.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gieseanw.wordpress.com/95/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gieseanw.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gieseanw.wordpress.com/95/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gieseanw.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gieseanw.wordpress.com/95/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gieseanw.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gieseanw.wordpress.com/95/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gieseanw.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gieseanw.wordpress.com/95/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gieseanw.wordpress.com&amp;blog=12012284&amp;post=95&amp;subd=gieseanw&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gieseanw.wordpress.com/2010/03/29/ascii-hangman/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/7496124d499d578df1e3a6ff85e7ae03?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gieseanw</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/03/hangman_banner.jpg" medium="image">
			<media:title type="html">Hangman_Banner</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/03/hangman_gamestart1.jpg?w=300" medium="image">
			<media:title type="html">Hangman_GameStart</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/03/hangman_design_notes1.jpg?w=222" medium="image">
			<media:title type="html">Hangman_Design_Notes1</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/03/hangman_design_notes2.jpg?w=128" medium="image">
			<media:title type="html">Hangman_Design_Notes2</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/03/hangman_highscore.jpg?w=300" medium="image">
			<media:title type="html">Hangman_Highscore</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/03/hangman_highscore_list.jpg?w=300" medium="image">
			<media:title type="html">Hangman_Highscore_list</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/03/hangman_design_notes3.jpg?w=300" medium="image">
			<media:title type="html">Hangman_Design_Notes3</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/03/hangman_vs_play.jpg" medium="image">
			<media:title type="html">Hangman_Vs_Play</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/03/hangman_vs_play2.jpg" medium="image">
			<media:title type="html">Hangman_Vs_Play2</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/03/hangman_usercontent.jpg" medium="image">
			<media:title type="html">Hangman_UserContent</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/03/hangman_usercontent2.jpg" medium="image">
			<media:title type="html">Hangman_UserContent2</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/03/hangman_newword.jpg" medium="image">
			<media:title type="html">Hangman_NewWord</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/03/hangman_newwordfail.jpg" medium="image">
			<media:title type="html">Hangman_NewWordFail</media:title>
		</media:content>
	</item>
		<item>
		<title>Building a DNS Resolver</title>
		<link>http://gieseanw.wordpress.com/2010/03/25/building-a-dns-resolver/</link>
		<comments>http://gieseanw.wordpress.com/2010/03/25/building-a-dns-resolver/#comments</comments>
		<pubDate>Thu, 25 Mar 2010 18:19:02 +0000</pubDate>
		<dc:creator>gieseanw</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[C/C++]]></category>
		<category><![CDATA[DNS]]></category>
		<category><![CDATA[networking]]></category>
		<category><![CDATA[select function]]></category>

		<guid isPermaLink="false">http://gieseanw.wordpress.com/?p=77</guid>
		<description><![CDATA[If you&#8217;ve ever had to turn a hostname into an IP address or the other way around in your C/C++ code, you probably called either gethostbyname() or gethostbyaddr(), and never thought twice about how those functions work. Well, they&#8217;re more complex than you might think, and they&#8217;re slow. Not excruciatingly slow, but slower than if [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gieseanw.wordpress.com&amp;blog=12012284&amp;post=77&amp;subd=gieseanw&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://gieseanw.files.wordpress.com/2010/03/dns-lookups.jpg"><img class="aligncenter size-medium wp-image-93" title="dns-lookups" src="http://gieseanw.files.wordpress.com/2010/03/dns-lookups.jpg?w=289&#038;h=300" alt="" width="289" height="300" /></a></p>
<p>If you&#8217;ve ever had to turn a hostname into an IP address or the other way around in your C/C++ code, you probably called either <a href="http://msdn.microsoft.com/en-us/library/ms738524%28VS.85%29.aspx">gethostbyname()</a> or <a href="http://msdn.microsoft.com/en-us/library/ms738521%28VS.85%29.aspx">gethostbyaddr()</a>, and never thought twice about <em>how</em> those functions work. Well, they&#8217;re more complex than you might think, and they&#8217;re <strong>slow</strong>.</p>
<p><span id="more-77"></span>Not excruciatingly slow, but slower than if you implement their functionality yourself, which is what I spent the last few weeks working on for my networking class.</p>
<p>So how do these functions work? Well, this requires an understanding of the Domain Name System or <a href="http://en.wikipedia.org/wiki/Domain_Name_System">DNS</a> for short. Here&#8217;s DNS 101:</p>
<p>You want to go to a site like Google, so you open your web browser and type www.google.com, or go through your bookmarks, or perhaps you have your homepage set to google.com. Either way, it remains transparent to you that www.google.com is an easy way to remember how to get to Google. But this name doesn&#8217;t uniquely identify Google in the sense that computers don&#8217;t understand the text, and the name google.com might redirect you to one of many of google&#8217;s servers, like one for www.google.es if you live in Spain.</p>
<p>What does uniquely identify Google is its Internet Protocol (<a href="http://en.wikipedia.org/wiki/Internet_Protocol">IP</a>) address, which is basically a unique series of numbers. Sort of like how your social security number identifies you, but nobody goes around calling you by it, because your name is just easier to remember. Another example is to think of all the contacts in your cell phone&#8217;s address book. How many of their phone numbers can you remember off-hand? Few, if any I&#8217;m guessing. It&#8217;s just easier to call &#8220;Amy&#8221; than it is to dial in their phone number. This is exactly the reason the DNS system was invented, so you wouldn&#8217;t have to remember IP addresses.</p>
<p>For anyone who has used gethostbyname() or gethostbyaddr(), this is obvious. But what <em>isn&#8217;t </em>obvious is the amount of work those functions go through to get you what you want; a simple translation of a host name into an IP address, or the other way around.</p>
<p>My project was to implement a multithreaded application that could resolve a batch file of N host names or IP addresses into IP addresses or host names, respectively. So how does it work?</p>
<p>Each thread takes a new batch entry to resolve, and does the following:</p>
<ul>
<li>Create a DNS Query</li>
<li>Put the DNS Query into a packet</li>
<li>Send the packet to the DNS server</li>
<li>Receive a response packet from the DNS server</li>
<li>Parse the packet, extract all the answers to our query</li>
<li>Output answers</li>
</ul>
<p>Sounds simple, right? The devil&#8217;s in the details.</p>
<p><!--more--></p>
<p><a href="http://www.ietf.org/rfc/rfc1035.txt">RFC 1035</a> is the official documentation for how all this is to implemented. I don&#8217;t suggest you actually read through the page, just get an understanding of how precise and complex the actual process is.</p>
<p>Depending on whether the next batch entry was a host name or a valid IP address, I would run either an Authoritative Query (to return an IP address) or a PTR query (to get a host name or authoritative name server). So I had to create a DNS packet, which in ASCII looks like the following (taken from RFC 1035):</p>
<p><img class="aligncenter size-medium wp-image-80" title="DNS Packet" src="http://gieseanw.files.wordpress.com/2010/03/dns-packet.jpg?w=322&#038;h=113" alt="" width="322" height="113" />And, broken down to the bit level, the Header section looks like this:<a href="http://gieseanw.files.wordpress.com/2010/03/dns-packet-header.jpg"><img class="aligncenter size-full wp-image-82" title="DNS Packet Header" src="http://gieseanw.files.wordpress.com/2010/03/dns-packet-header.jpg?w=450&#038;h=266" alt="" width="450" height="266" /></a><br />
Boring and unintelligible you say? Bollocks. The RFC is actually very clear about what each field <em>means</em>, but it leaves the implementation up to you. In general, these are handled through direct manipulation of bit strings. Making the header section is actually fairly easy, as a header is always the same size no matter what. But what about the question section I was sending?</p>
<p><a href="http://gieseanw.files.wordpress.com/2010/03/dns-packe-question.jpg"><img class="aligncenter size-full wp-image-83" title="DNS Packe Question" src="http://gieseanw.files.wordpress.com/2010/03/dns-packe-question.jpg?w=450&#038;h=180" alt="" width="450" height="180" /></a>Setting the type of question was easy (PTR or A, both translate to 1 byte numbers that can be #defined), as was setting the class of question (Always internet, which also translates to a 1 byte number). Properly setting Qname was kind of hard in implementation, although theoretically it sounds fine.</p>
<p>First, I had to calculate the number of bytes I would need, so I could create a packet of proper size, then I had to create the name and insert it into the right location in the packet. We are simply manipulating bit strings after all, here. So first the DNS header was inserted, indicating 1 question to follow, then the question section followed.</p>
<p>All question names have to be converted into a special format according to protocol. A question like www.google.com becomes 3www6google3com0, where the numbers indicate the #of bytes to follow, and replace all periods (to separate top-level, second-level, etc. domains) the 0 appended to the end is a signal meaning &#8220;end of name&#8221;. So how many bytes had to be reserved is simple addition: length of name + 2, the extra 2 coming from the appending of the &#8217;3&#8242; at the start and the &#8217;0&#8242; at the end. Thanks to ASCII, one character takes up 1 byte, so there&#8217;s no extra math involved.</p>
<p>Turning an IP address into a name is a little more difficult: an IP like 123.45.67.8 has to be turned into 8.67.45.123.IN-ADDR.ARPA, which is then turned into 18267245312327IN-ADDR4ARPA, or for you humans out there [1]8[2]67[2]45[3]123[7]IN-ADDR[4]ARPA where the brackets indicate a period was replaced with a 1 byte decimal representing the number of characters to follow.</p>
<p>As you can see, it&#8217;s a little less trivial than just replacing periods with numbers, because the IP address is not entirely reversed; each substring between periods gets reversed. Still, a little use of the <a href="http://msdn.microsoft.com/en-us/library/ftsafwz3%28VS.80%29.aspx">strtok_s</a> function helps out a lot!</p>
<p>This question resource record was copied using the <a href="http://www.cplusplus.com/reference/clibrary/cstring/memcpy/">memcpy</a> function to put all our data into our char* packet (which, let me remind you is actually a string of bits!)</p>
<p>After this, it becomes a simple matter of sending the packet to our local DNS server, right?</p>
<p><!--more-->You knew it wasn&#8217;t that easy! How DO you find out the local DNS server to ping anyway??? Hard coding the value is a very very bad idea, so we had to find the DNS server dynamically.</p>
<p>This was done with a little help from a function called <a href="http://msdn.microsoft.com/en-us/library/aa365968%28VS.85%29.aspx">GetNetworkParams()</a>, which helps one obtain information like Host Name, Domain Name, and yes, Local DNS Servers. After we got a primary DNS Server IP, we could open UDP sockets and send our packets to them.</p>
<p>OK, so far we have found a DNS Server and created the packet we want to send. We just need a socket for communication. DNS typically runs over UDP sockets, which are faster than TCP, though less reliable. I used UDP sockets, but because they&#8217;re unreliable, I had to have a retransmission scheme in case the packet was lost. This can be accomplished with a little help from the <a href="http://msdn.microsoft.com/en-us/library/aa365968%28VS.85%29.aspx">select()</a> function, which will allow a request to time out instead of hang indefinitely.</p>
<p>Using the function properly is a little difficult at first, and there aren&#8217;t a  whole lot of great examples out there, so here&#8217;s my code:</p>
<p><a href="http://gieseanw.files.wordpress.com/2010/03/select.jpg"><img class="aligncenter size-full wp-image-87" title="select" src="http://gieseanw.files.wordpress.com/2010/03/select.jpg?w=450&#038;h=293" alt="" width="450" height="293" /></a>There&#8217;s a couple things to note here. First, one must create a timeval structure which allows you to specify timeout time in seconds (timeval-&gt;sec) and milliseconds (timeval-&gt;usec). the name of my UDP socket is sock, and was instantiated earlier. Next, you must create a fd_set structure to specify which sockets you will wait on. I named my structure Sockets. the fd_count field specifies the number of sockets to wait on, and the fd_array[0] is setting the first item of the array of sockets to my socket, sock.</p>
<p>Then, I send my packet to the server and wait for 30 seconds via the select function. If a response is received from the server, I process it and exit the loop, but what&#8217;s more important here is the case where the select() times out. After processing why the select function failed (time out or socket error), you MUST reset your fd_set structure or else any future calls to select using that structure will immediately fail!</p>
<p>My retransmission strategy was to try a total of three times to get the packet to the server, and if it times out all three times, the output of the program later will inform the user of this.</p>
<p><!--more--></p>
<p>Now that we&#8217;ve located our DNS server, created our packet, opened a socket, successfully sent our data, and received a response from the server, here comes the easy part! Well, not really, there aren&#8217;t any really easy parts in this project! All the data we received into our buffer is again a string of bits that we must manually separate into meaningful blocks of data. <a href="http://www.binarytides.com/blog/dns-query-code-in-c-with-winsock-and-linux-sockets/">Binary Tides </a>has an excellent article that fully illustrates parsing the received data.</p>
<p>Our received packet is in exactly the same format as the DNS packet we sent to the server: DNS Header, Question, Answer, Authority, and Additional sections. Since the DNS Header is of fixed length we can easily read in how many answer, authoritative, and additional RRs are contained in the packet. First things first, though &#8211;we must read the flags from the header section to determine if there was an error of some sort reported by the server.</p>
<p>The flags section of the header will indicate response messages, similar to the &#8220;200 OK&#8221; responses you get from a HTTP GET request. The thing is, though, that they&#8217;re represented as a four-bit number (the &#8220;RCODE&#8221; part of the above figure). There is no basic data type we can cast into just four bits so what I did is grab 1 byte with an unsigned short, and then <a href="http://en.wikipedia.org/wiki/Bitwise_operation">bit-mask</a> the top nybble with 0&#8242;s so I would get something like 0000 0010 instead of possibly 0010 0010, which indicates a response code of 34 instead of 2, and there does not exist a response code of 34. What&#8217;s more, a response code of 2 indicates that the server failed to process the query, so without bit-masking we may just assume the server could not find a DNS entry instead of the real reason.</p>
<p>So after we receive a flag of 0 (no error), we can parse out all our answers. The manner to do so involves carefully separating bits out of the bitstring, via casting into a variety of types. I personally based my code off the Binary Tides article above, so I could do no better job explaining how it&#8217;s done than that author.</p>
<p>Now comes the (actual) easy part: processing all the data! After all the records in batch mode have been processed, we have a wealth of information. We can calculate average wait times, percentage of failed queries, percentage of records with no DNS entries, or take it a step further and calculate statistics based on # of threads run, # of entries in the batch file, whether the project is run in debug or release mode, and then compare all our results to those had we just used gethostbyname() and gethostbyaddr().</p>
<p>NOTE: Unless you are hosting your own domain name server through something like <a href="http://www.simpledns.com/">Simple DNS</a>, I highly advise <strong>against </strong>running a batch file of more than a few entries as well as more than a few threads! The sheer volume of DNS queries coming into the DNS server could overload it and either crash it or cause network outages for other users on the network! This could be viewed as a malicious network attack (similar to a DOS attack) and it <em>can</em> be traced back to your computer!</p>
<p>Ok, now that I&#8217;ve got that out of the way, I can tell you this: I was on the University of Dayton&#8217;s network and could not run my project for large batches of data due to the above stated information. Additionally, Simple DNS could not be properly configured because UD&#8217;s DNS servers refuse to transfer records to other computers (most likely for security reasons). BUT, I was able to gather some overall conclusions based on my own small tests, and reading the reports from the few other people in my class who also built DNS resolvers.</p>
<p>This project is much, much faster than gethostbyname() and gethostbyaddr() for all sizes of data and number of threads running. Runs of even very large batch files could be as much as 5-10 times faster! This is probably due to the fact that the MSDN functions are more robust and secure, but the difference is astonishing. Also, projects actually seemed to run faster on debug versions than release mode. Strange, considering STL insertion is about 50 times faster in release mode. I do not know why this is, and can&#8217;t even really guess at it.</p>
<p>So there you have it, a DNS Resolver, built over the course of many hours during a two-week span. It is a huge learning experience, and really teaches you that re-inventing the wheel can cost many hours of time lost. Had one not known functions like gethostbyname() existed, they may have tried to do something like this, spending 60 hours when they could have spent 10 minutes reading the MSDN function documentation.</p>
<p>Also, it teaches you some nuts-and bolts about what has to go on when you make a request as simple as &#8220;www.google.com&#8221; into your URL toolbar of your browser.</p>
<p>Finally, if you want to look at the DNS packets (as well as other types of packets) streaming across your network, I suggest you install <a href="http://www.wireshark.org/">Wireshark</a>, a free application for sniffing your packets. The program was so essential to me during the building of this project, as it allowed me to carefully examine each of my malformed packets and find out what I was doing wrong.</p>
<p>Thanks for reading, if you got this far. This was one of my most difficult and complex projects to date. If you want the source code&#8230; well too bad <img src='http://s0.wp.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' />  It could be used for malicious purposes and I don&#8217;t want to freely distribute it. If you have any questions about the whole DNS lookup process, though, I would be glad to help! Find my e-mail address on my &#8220;About Me&#8221; Page.</p>
<br /> Tagged: <a href='http://gieseanw.wordpress.com/tag/cc/'>C/C++</a>, <a href='http://gieseanw.wordpress.com/tag/dns/'>DNS</a>, <a href='http://gieseanw.wordpress.com/tag/networking/'>networking</a>, <a href='http://gieseanw.wordpress.com/tag/select-function/'>select function</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gieseanw.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gieseanw.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gieseanw.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gieseanw.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gieseanw.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gieseanw.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gieseanw.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gieseanw.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gieseanw.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gieseanw.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gieseanw.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gieseanw.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gieseanw.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gieseanw.wordpress.com/77/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gieseanw.wordpress.com&amp;blog=12012284&amp;post=77&amp;subd=gieseanw&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gieseanw.wordpress.com/2010/03/25/building-a-dns-resolver/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/7496124d499d578df1e3a6ff85e7ae03?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gieseanw</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/03/dns-lookups.jpg?w=289" medium="image">
			<media:title type="html">dns-lookups</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/03/dns-packet.jpg?w=300" medium="image">
			<media:title type="html">DNS Packet</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/03/dns-packet-header.jpg" medium="image">
			<media:title type="html">DNS Packet Header</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/03/dns-packe-question.jpg" medium="image">
			<media:title type="html">DNS Packe Question</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/03/select.jpg" medium="image">
			<media:title type="html">select</media:title>
		</media:content>
	</item>
		<item>
		<title>Think You&#8217;re Good At Connect 4?</title>
		<link>http://gieseanw.wordpress.com/2010/02/22/think-youre-good-at-connect-4/</link>
		<comments>http://gieseanw.wordpress.com/2010/02/22/think-youre-good-at-connect-4/#comments</comments>
		<pubDate>Mon, 22 Feb 2010 02:52:31 +0000</pubDate>
		<dc:creator>gieseanw</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[MiniMax]]></category>
		<category><![CDATA[openGL]]></category>

		<guid isPermaLink="false">http://gieseanw.wordpress.com/?p=58</guid>
		<description><![CDATA[I won&#8217;t question your adeptness at a favorite childhood game, but my bot Herbert will. Myself and a few other guys developed Herbert for our final project in AI class, and he is frustratingly unbeatable. After a game or two against him, you might consider an early retirement from the Connect 4 world. &#8216;Herbert&#8217; as [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gieseanw.wordpress.com&amp;blog=12012284&amp;post=58&amp;subd=gieseanw&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://gieseanw.files.wordpress.com/2010/02/connectfour1.jpg"><img class="aligncenter size-medium wp-image-59" title="ConnectFour1" src="http://gieseanw.files.wordpress.com/2010/02/connectfour1.jpg?w=300&#038;h=232" alt="" width="300" height="232" /></a></p>
<p>I won&#8217;t question your adeptness at a favorite childhood game, but my bot Herbert will. Myself and a few other guys developed Herbert for our final project in AI class, and he is frustratingly unbeatable. After a game or two against him, you might consider an early retirement from the Connect 4 world.</p>
<p><span id="more-58"></span>&#8216;Herbert&#8217; as I affectionately named him is a piece of software that implements a <a href="http://en.wikipedia.org/wiki/Minimax">MiniMax</a> with Alpha Beta Cutoffs search algorithm. Basically all this means is that Herbert will look at the current game state board, generate the possible moves one could make from that board, then the possible moves from those boards, and so on, creating a large tree of possible boards which it then ranks as optimal or suboptimal. It will make a move towards a board it deems the best one.</p>
<p>As the number of all possible boards for even something like a Connect 4 board is very, very large, Herbert can&#8217;t look at all of them, and therefore must make some decisions based on just what he can foresee, like a human player. To ensure Herbert wouldn&#8217;t spend too much time searching, we implemented an <a href="http://en.wikipedia.org/wiki/Iterative_deepening">iterative deepening</a> loop so that he could break out when he found a win or ran out of allotted time to search.</p>
<p>The result is a bot that is nearly unbeatable. Herbert performed very well in his AI debut-at a tournament against the other Connect 4 bots in the class. Due to a mixup, we played the majority of the games at the tournament with an older version of Herbert, and got the new, beefed up Herbert just before tournament end, and proceeded to whoop every bot we came up against. Too bad Herbert v2&#8242;s performance wasn&#8217;t good enough; we came in third place or so out of eight teams. Herbert 2.0, though, went undefeated.</p>
<p>The really cool thing about a MiniMax algorithm is that it will play optimally well against an optimal opponent (i.e. another Connect 4 bot), provided you &#8216;rank&#8217; your generated boards properly to choose the right path. using Alpha Beta cutoffs effectively can also narrow the search and greatly cut down search time. What Alpha Beta cutoffs basically mean is that we can determine ahead of time whether evaluating boards down a certain branch of the tree will possibly affect our current &#8216;best path&#8217; or not, and if it doesn&#8217;t, we don&#8217;t search it!</p>
<p>My personal responsibilities on the project were vast; I can not claim credit for the majority implementation of the MiniMax algorithm or most of the functions used to evaluate boards for optimality (although I spent A LOT of time helping the guys who did implement these improve them and debug them), I created the graphical user interface (GUI), or at least about 98% of it.</p>
<p>If you&#8217;ve read any of my older posts, you may have stumbled across my <a href="http://gieseanw.wordpress.com/2010/02/13/an-homage-to-matt-groening/">rendition</a> of the Simpson&#8217;s living room in 3D. Building this scene took at least as long as that one. First of all, I do not claim to be anywhere near an expert in openGL, but I&#8217;m darn proud of how this thing turned out.</p>
<p>Again, the entire scene is rendered using openGL primitives (and a texture or two). The thing is&#8230; How do you create a connect 4 board? Each &#8216;slot&#8217; is basically a cube with a spherical/cylindrical hole in it, and openGL doesn&#8217;t have a native shape like that to my knowledge. So I had two options: either define the vertices of the shape myself, or approximate it using openGL primitives. I chose the latter. Here&#8217;s how I did it:</p>
<p>openGL natively supports rendering toruses (donut shapes): so I started by rendering just the open slots, generating a board that looked something like this:</p>
<p style="text-align:center;"><a href="http://gieseanw.files.wordpress.com/2010/02/connectfour2.jpg"><img class="aligncenter size-full wp-image-60" title="ConnectFour2" src="http://gieseanw.files.wordpress.com/2010/02/connectfour2.jpg?w=450" alt=""   /></a></p>
<p>Now, from here, we can just generate cubes (stretched a bit, of course) to cover the gaps just perfectly enough, like so:</p>
<p style="text-align:center;"><a href="http://gieseanw.files.wordpress.com/2010/02/connectfour3.jpg"><img class="aligncenter size-full wp-image-61" title="ConnectFour3" src="http://gieseanw.files.wordpress.com/2010/02/connectfour3.jpg?w=450" alt=""   /></a></p>
<p>This solution works well enough, but is hardly perfect. If you look closely enough, you can see that little gap of white. The same is true of the actual board, although it&#8217;s so subtle you&#8217;d hardly ever notice it (except for me, who spent days looking at, to me it&#8217;s glaringly obvious).</p>
<p>The result is that you look like you have&#8230; a cube with a circular hole cut out. Perfect.</p>
<p>I&#8217;d like to say after getting the board to render perfectly all the pieces just fell into place from there, but that&#8217;s far from the truth. I had to implement a mouse tracker that would render a transparent piece to follow the top of the board, so that a user would know which column they&#8217;d be dropping their piece in:</p>
<p><a href="http://gieseanw.files.wordpress.com/2010/02/connectfour4.jpg"><img class="aligncenter size-full wp-image-62" title="ConnectFour4" src="http://gieseanw.files.wordpress.com/2010/02/connectfour4.jpg?w=450" alt=""   /></a>I just couldn&#8217;t seem to get rid of that little dark patch you see in the transparent piece, so I just had to live with it.</p>
<p>From there I proceeded to create a little animation that would show your piece falling into place:</p>
<p><a href="http://gieseanw.files.wordpress.com/2010/02/connectfour5.jpg"><img class="aligncenter size-medium wp-image-63" title="ConnectFour5" src="http://gieseanw.files.wordpress.com/2010/02/connectfour5.jpg?w=300&#038;h=277" alt="" width="300" height="277" /></a>And look at the shadow underneath the board! That was me, too! The shadow is a perfect rendition of the board in real time. it updates with each falling piece!</p>
<p>So while the entire scene is rendered in 3D we decided to let the user look around a bit. After the click the right mouse button, they can rotate the scene at will to look at it from all angles. Other teams did a similar thing, but they thought that 3D rotation would ruin their 2D selection boxes and break the user-selection for their game, so they had a 3D scene that couldn&#8217;t be rotated&#8230;essentially making it a 2D scene (in that case, why bother?).</p>
<p>I had an easy solution for that (no, not 3D picking): After the user let up on the right mouse the scene would &#8216;snap back&#8217; into place. Any functions relating to the actual game were disabled during rotation as an extra precaution.</p>
<p>Here&#8217;s the scene from a few different angles:</p>
<p><a href="http://gieseanw.files.wordpress.com/2010/02/connectfour6.jpg"><img class="alignleft size-medium wp-image-64" title="ConnectFour6" src="http://gieseanw.files.wordpress.com/2010/02/connectfour6.jpg?w=300&#038;h=232" alt="" width="300" height="232" /></a><a href="http://gieseanw.files.wordpress.com/2010/02/connectfour7.jpg"><img class="alignright size-medium wp-image-65" title="ConnectFour7" src="http://gieseanw.files.wordpress.com/2010/02/connectfour7.jpg?w=300&#038;h=232" alt="" width="300" height="232" /></a></p>
<p><img title="YayClipping" src="http://gieseanw.files.wordpress.com/2010/02/yayclipping.jpg?w=300&#038;h=232" alt="Yay Clipping!" width="300" height="232" /></p>
<p>Finally, I built a little &#8216;win screen&#8217;. I should just call it a &#8216;CPU win screen&#8217; because I haven&#8217;t seen a human beat Herbert since when he only made random valid moves.</p>
<p>I must take a second now to thank my team for helping put this whole thing together. They were motivated, dedicated, and had a high standard for quality: Andres (MiniMax optimization, board evaluation) Zac (GUI textures, help with timer), Mike (board evaluation functions) and TJ (original MiniMax w/ alpha beta implementation).</p>
<p>Finally, I want to thank all those &#8220;Hallway&#8221; testers I grabbed to help test the game&#8211;GUI and Herbert alike&#8211; family, friends, and roomates. I suck at Connect 4 personally, so having a few good players to test Herbert for weaknesses really helped.</p>
<p>Our professor gave out two automatic A&#8217;s for the assignment: the team with the best overall record in the tournament, and the team with the best GUI (and one team couldn&#8217;t win both). We won the &#8216;Best GUI&#8217; award. Awesome.</p>
<p>Some notable things about the project:</p>
<ul>
<li>There&#8217;s no 2-person play; it&#8217;s always Human versus CPU</li>
<li>You have the option after each game to choose whether the human or CPU will play first.</li>
<li>To play against other bots, a human &#8216;data enterer&#8217; was needed to translate their bot&#8217;s move to the other person&#8217;s game so they would stay synchronized (i.e. no networking code was involved here)</li>
<li>The team that ended up winning the tournament I personally feel also had a superior GUI rendered in C#, and I must tip my hat to their expertise.</li>
<li>If I could make some more optimizations for the CPU to play against a Human, I would make a few changes: like making semi-random moves sometimes, accounting for the human to make some mistakes, so maybe be a little more aggressive; a difficulty meter that one could set to be as hard or easy as they wanted; and a few other things.</li>
<li>I would implement a few threading techniques so that the user can interact with the scene while Herbert is thinking</li>
<li>Herbert is programmed to think for just under 1 minute, as that was the time allotted for each move. He moves sooner the longer the game goes on (smaller search space, and definite wins/losses spotted).</li>
</ul>
<div id="attachment_70" class="wp-caption aligncenter" style="width: 310px"><a href="http://gieseanw.files.wordpress.com/2010/02/connectfour8.jpg"><img class="size-medium wp-image-70" title="ConnectFour8" src="http://gieseanw.files.wordpress.com/2010/02/connectfour8.jpg?w=300&#038;h=232" alt="Win Screen" width="300" height="232" /></a><p class="wp-caption-text">The House always wins</p></div>
<p>That&#8217;s all I have to say about Herbert and the MiniMax implementation! If you have further questions or want the full .exe, just email me (my details can be found on the &#8216;About Me&#8217; page).</p>
<br /> Tagged: <a href='http://gieseanw.wordpress.com/tag/ai/'>AI</a>, <a href='http://gieseanw.wordpress.com/tag/minimax/'>MiniMax</a>, <a href='http://gieseanw.wordpress.com/tag/opengl/'>openGL</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gieseanw.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gieseanw.wordpress.com/58/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gieseanw.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gieseanw.wordpress.com/58/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gieseanw.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gieseanw.wordpress.com/58/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gieseanw.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gieseanw.wordpress.com/58/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gieseanw.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gieseanw.wordpress.com/58/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gieseanw.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gieseanw.wordpress.com/58/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gieseanw.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gieseanw.wordpress.com/58/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gieseanw.wordpress.com&amp;blog=12012284&amp;post=58&amp;subd=gieseanw&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gieseanw.wordpress.com/2010/02/22/think-youre-good-at-connect-4/feed/</wfw:commentRss>
		<slash:comments>32</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/7496124d499d578df1e3a6ff85e7ae03?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gieseanw</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/02/connectfour1.jpg?w=300" medium="image">
			<media:title type="html">ConnectFour1</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/02/connectfour2.jpg" medium="image">
			<media:title type="html">ConnectFour2</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/02/connectfour3.jpg" medium="image">
			<media:title type="html">ConnectFour3</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/02/connectfour4.jpg" medium="image">
			<media:title type="html">ConnectFour4</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/02/connectfour5.jpg?w=300" medium="image">
			<media:title type="html">ConnectFour5</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/02/connectfour6.jpg?w=300" medium="image">
			<media:title type="html">ConnectFour6</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/02/connectfour7.jpg?w=300" medium="image">
			<media:title type="html">ConnectFour7</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/02/yayclipping.jpg?w=300" medium="image">
			<media:title type="html">YayClipping</media:title>
		</media:content>

		<media:content url="http://gieseanw.files.wordpress.com/2010/02/connectfour8.jpg?w=300" medium="image">
			<media:title type="html">ConnectFour8</media:title>
		</media:content>
	</item>
	</channel>
</rss>
