<?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>Antimatroid, The</title>
	<atom:link href="http://antimatroid.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://antimatroid.wordpress.com</link>
	<description>niche for the aesthetics, mathematics and computer science</description>
	<lastBuildDate>Tue, 01 Dec 2009 14:00:24 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='antimatroid.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/4f7d497af5ea099e7d73389ebe338967?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>Antimatroid, The</title>
		<link>http://antimatroid.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://antimatroid.wordpress.com/osd.xml" title="Antimatroid, The" />
		<item>
		<title>The next decade of the Internet</title>
		<link>http://antimatroid.wordpress.com/2009/12/01/the-next-decade-of-the-internet/</link>
		<comments>http://antimatroid.wordpress.com/2009/12/01/the-next-decade-of-the-internet/#comments</comments>
		<pubDate>Tue, 01 Dec 2009 14:00:24 +0000</pubDate>
		<dc:creator>lewellen</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Network Neutrality]]></category>
		<category><![CDATA[Opinion]]></category>
		<category><![CDATA[Smartphones]]></category>
		<category><![CDATA[Worldwide Internet Languages]]></category>

		<guid isPermaLink="false">http://antimatroid.wordpress.com/?p=1240</guid>
		<description><![CDATA[This post marks the return of The Antimatroid after a four month hiatus. I will be resuming my monthly publication format. Next month&#8217;s post will be on multi-agent consensus forming followed by infectious diseases modeling.
Last month, specifically- October 29, 2009, marked the 40th year of the Internet- which got me thinking a bit about the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=antimatroid.wordpress.com&blog=4448583&post=1240&subd=antimatroid&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><i>This post marks the return of The Antimatroid after a four month hiatus. I will be resuming my monthly publication format. Next month&#8217;s post will be on multi-agent consensus forming followed by infectious diseases modeling.</i></p>
<p>Last month, specifically- October 29, 2009, marked the 40th year of the Internet- which got me thinking a bit about the direction the Internet is heading in and how people will ultimately utilize the Internet in the future. Part of this thought exercise is thinking what devices people will use to connect to the Internet, what they will do once connected and what type of networks their data will travel over. Naturally, thinking about what information those devices are capable of collecting, presenting, processing; what people will share, interact and consume while connected; and finally the technology behind the network, who owns the network and how it is regulated. The other half of this exercise, is looking at the trajectory that history has provided us for extrapolation.</p>
<p>According to Gartner, there were <A href="http://www.gartner.com/it/page.jsp?id=1126812">41.0 million smartphones</a> sold worldwide in the second quarter of 2009. At present, there ought to be roughly a billion smartphones worldwide, each of these phones is connected to some kind of network capable of accessing the Internet. Most of these phones have built-in cameras, voice recorders, GPS and accelerometers. Just about any other sensor could be added to these phones. Imagine each one sending up that sensor data to The Cloud- GPS information coupled with images could allow for image recognition to be performed real-time to tell the user about what they are looking at, weather sensors could be added to capture accurate weather information to provide more accurate weather models. Another aspect to consider- each smartphone has processing power of 500Mhz to 1Ghz. That is a lot of potential processing power left untapped, on the order of an exahertz. Telecoms could lease out this processing power to whomever and make a bundle if the margin is right.</p>
<p>With all this information that can come up from smartphones as well as traditional machinery, the Internet becomes much more real-time and much more focused. To make sense of this information, there will continue to be a need for efficient and effective searching- Google isn&#8217;t going anywhere- but it will have to become more specialized providing location aware searching, e.g., being able to walk into a bookstore and having instructions on how to find a copy of an original print favorite of yours down to the bookcase and row. Aggregation sites that understand how to filter down the data and present it in a meaningful and insightful way will be necessary to make sense of all the data. Sites that present media from multiple sites, multiple social networks and results from multiple search engines will gain value. The ability to take in multiple data streams in a standardized way is important- a common interface for real-time data. </p>
<p>Data, obviously, isn&#8217;t just text, it is audio, pictures and video. We saw how streaming media was a boom in the late 90s for music. The emergence of VoIP as an effective replacement for telephone lines- both residential and commercial- has seen adoption in leaps and bounds. News organizations have adopted the net in varying degrees allowing for much faster distribution of news as it happens. The remaining media is television. YouTube, Hulu, Netflix have seen the commercial benefits of bringing streaming video to the world. Traditional media outlets are streaming their programs online &#8211; Fox, CBS, ABC, NBC etc all have fantastic options available for free. The trend here being that we can bring all of our traditional media onto a single delivery system: news, documents, images, audio, video &#8211; all the media we&#8217;ve come to adopt over time &#8211; can be delivered to you on a single pipe.</p>
<p>People will continue to share information, but the focus will be on better management of their networks, their social circles to be more precise- both virtual and physical. Networks like Facebook and LinkedIn do a decent job now of connecting people with one another, but fail to adequately manage which information is dispersed amongst the associates in our networks. The focus on managing, marketing and protecting our identities and personas will become more prominent; publishing, sharing and distributing information that we find, produce and rehash will become easier. </p>
<p>Of course this is a very North American view of the Internet. It is estimated that 25% of the world&#8217;s population is connected to the internet according to <a href="http://www.internetworldstats.com/stats.htm" target="blank">Internet World Stats</a>. Of that quarter, Asia represents roughly 42.6% of all internet users followed by Europe at 24.1% and North America at 14.6%. Among all Internet users, 27.6% speak English, 22.2% Chinese and 7.9% Spanish. Unsurprisingly, the corresponding number of web pages by those languages are not proportionate to their language base. English website constitute 68.4% of all pages followed by Japanese at 5.9% and German at 5.8% according to <a target="blank" href="http://www.clickz.com/408521">ClickZ</a>. When you get down to it, the Internet contains a lot of information, but most likely in a language that the user doesn&#8217;t speak, unless they happen to know English. I believe that we will continue to see English as the dominate language of the web until new standards come in to place that allow for better support of the Unicode character encoding at each part of the Internet technology stack. At which time, I would expect to see page share by language to be proportionate to world language shares. I would not expect to see an increase in the number of Middle East and African users given the more pressing matters of each region- as of now each represents less than 4% of internet users. Naturally, as language shares normalize, automated translation will become increasingly important as great ideas are not limited to just one language.</p>
<p>As I draw to a close, I&#8217;d like to mention one more area of interest: regulation. I believe that this area will become more contentious as the number of individuals on the Internet from minority nations increases in the coming decade. It should seem reasonable that anyone, anywhere has the right to access, produce and discuss the lawful content of their choice without obstruction from a foreign body. Problem being, what is lawful content? We should all be able to recognize that there exist ideas that should be allowed to spread freely, even when we do not agree with those ideas and that that information should be spread freely unobstructed by any entity. </p>
<p>The second aspect to this problem of regulation is how people will be charged to access the Internet. Internet Service Providers should not charge customers to access certain sites, doing so is a form of censorship as well as a form of control a companies primary resource: users. ISPs could have the ability to reduce a website&#8217;s user traffic by charging those users money to access that site and thus reducing the number of users that might go to a website and thus reducing the profitability of that website. Likewise, if an ISP did not want users to visit a particular website, they could drop all packet requests to that website or return that the site does not exist. practices such as these are why it is important for different nations to adopt the policy of Network Neutrality. As the Internet reaches its next phase of development it will become increasingly important that the foundations that made it so popular are not disregarded in favor of those motivated by political or corporate ideologies.</p>
<p>The Internet has proven to be the truest of democratic forms, a wildly successful bazaar, a comprehensive library and ultimately a platform that enables people from every background to access, distribute and discuss information. I suspect that we will see the Internet become real time, it will be able to provide us with location aware content, be on the smallest and largest of gadgets from our cellphones to computers. We will access all of our information from the Internet: music, radio, television and news. It will become easier to manage our social networks and personal data. The shift from English to local languages will begin to build momentum as Unicode support becomes more widely adopted. There will be potential for underrepresented regions to start having a presence on the Internet. Last but not least, it will start to see an increased trend towards less censorship and more regulation towards keeping it an open platform.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/antimatroid.wordpress.com/1240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/antimatroid.wordpress.com/1240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/antimatroid.wordpress.com/1240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/antimatroid.wordpress.com/1240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/antimatroid.wordpress.com/1240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/antimatroid.wordpress.com/1240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/antimatroid.wordpress.com/1240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/antimatroid.wordpress.com/1240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/antimatroid.wordpress.com/1240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/antimatroid.wordpress.com/1240/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=antimatroid.wordpress.com&blog=4448583&post=1240&subd=antimatroid&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://antimatroid.wordpress.com/2009/12/01/the-next-decade-of-the-internet/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/62c32c6293d483fc7e1d545c4b9a0ac3?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">lewellen</media:title>
		</media:content>
	</item>
		<item>
		<title>Busy month</title>
		<link>http://antimatroid.wordpress.com/2009/07/01/busy-month/</link>
		<comments>http://antimatroid.wordpress.com/2009/07/01/busy-month/#comments</comments>
		<pubDate>Wed, 01 Jul 2009 07:00:05 +0000</pubDate>
		<dc:creator>lewellen</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://antimatroid.wordpress.com/?p=769</guid>
		<description><![CDATA[Between a busy month at work and juggling the duties associated with buying a home, I&#8217;ve haven&#8217;t had the time to write anything up for the month of July. I do have some interesting stuff in the works for August and following months. Until then, I&#8217;m sure you&#8217;ll find something worth reading in the archive.
 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=antimatroid.wordpress.com&blog=4448583&post=769&subd=antimatroid&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Between a busy month at work and juggling the duties associated with buying a home, I&#8217;ve haven&#8217;t had the time to write anything up for the month of July. I do have some interesting stuff in the works for August and following months. Until then, I&#8217;m sure you&#8217;ll find something worth reading in the archive.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/antimatroid.wordpress.com/769/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/antimatroid.wordpress.com/769/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/antimatroid.wordpress.com/769/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/antimatroid.wordpress.com/769/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/antimatroid.wordpress.com/769/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/antimatroid.wordpress.com/769/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/antimatroid.wordpress.com/769/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/antimatroid.wordpress.com/769/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/antimatroid.wordpress.com/769/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/antimatroid.wordpress.com/769/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=antimatroid.wordpress.com&blog=4448583&post=769&subd=antimatroid&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://antimatroid.wordpress.com/2009/07/01/busy-month/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/62c32c6293d483fc7e1d545c4b9a0ac3?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">lewellen</media:title>
		</media:content>
	</item>
		<item>
		<title>Sudoku Solver in Haskell</title>
		<link>http://antimatroid.wordpress.com/2009/06/01/sudoku-solver-in-haskell/</link>
		<comments>http://antimatroid.wordpress.com/2009/06/01/sudoku-solver-in-haskell/#comments</comments>
		<pubDate>Mon, 01 Jun 2009 07:00:03 +0000</pubDate>
		<dc:creator>lewellen</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Sudoku]]></category>

		<guid isPermaLink="false">http://antimatroid.wordpress.com/?p=712</guid>
		<description><![CDATA[This month will be a bit of short article since I haven&#8217;t had a whole lot of time on my hands lately. Haskell is a wonderful little language that has begun to pick up a bit of moment in the past year that I&#8217;ve been playing with on-and-off now for several years. Since I don&#8217;t [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=antimatroid.wordpress.com&blog=4448583&post=712&subd=antimatroid&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>This month will be a bit of short article since I haven&#8217;t had a whole lot of time on my hands lately. Haskell is a wonderful little language that has begun to pick up a bit of moment in the past year that I&#8217;ve been playing with on-and-off now for several years. Since I don&#8217;t post enough on Haskell, I figured I&#8217;d post my bare-bones Haskell Sudoku Solver.</p>
<pre>
import Data.List
import Data.Maybe

toRowColumn :: Int -&gt; (Int, Int)
toRowColumn index = (r, c)
	where	r = div index 9
		c = mod index 9

toIndex :: (Int, Int) -&gt; Int
toIndex (r, c) = r * 9 + c

toRegion :: (Int, Int) -&gt; Int
toRegion (r, c) = (div r 3) * 3 + (div c 3)

columnIndicies :: Int -&gt; [Int]
columnIndicies c = [c, c + 9..80]

regionIndicies :: Int -&gt; [Int]
regionIndicies g = [toIndex(r + x, c + y) |
		x &lt;- [0..2],
		y  [Int]
rowIndicies r = [9 * r..9 * (r + 1) - 1]

values :: [Int] -&gt; [Int] -&gt; [Int]
values board indicies = filter (&gt;0) (map (board!!) indicies)

possibleValues :: [Int] -&gt; (Int, Int) -&gt; [Int]
possibleValues board rowColumn =
	foldl () [1..9] (
	  map (values board) (
	    map (f -&gt; (fst f . snd f) rowColumn) (
	      zip [rowIndicies, columnIndicies, regionIndicies] [fst, snd, toRegion]
	    )
	  )
	)

validBoard :: [Int] -&gt; Bool
validBoard board = (length board == 81) &amp;&amp; (and $ map (==0) l)
	where	l = map length s
		s = map ([1..9]) v
		v = [values board (xIndicies x) |
			x &lt;- [0..8],
			xIndicies  Bool
solvedBoard board = and $ map (&gt;0) board

hasUnassigned :: [Int] -&gt; Bool
hasUnassigned board = isJust $ elemIndex 0 board

assignFirstUnassigned :: [Int] -&gt; Int -&gt; [Int]
assignFirstUnassigned (b:bs) value
	| b == 0 = value : bs
	| otherwise = b : (assignFirstUnassigned bs value)

possibleBoards :: [Int] -&gt; [Int] -&gt; [[Int]]
possibleBoards board possibleAssignments = map (assignFirstUnassigned board) possibleAssignments

solve :: [Int] -&gt; [[Int]]
solve board
	| not (validBoard board) = [[]]
	| solvedBoard board = [board]
	| not (hasUnassigned board) = [[]]
	| otherwise = concated
	where	concated = concat mapped
		mapped = map solve filtered
		filtered = filter (not . null) possibleSolved
		possibleSolved = possibleBoards board possibleAssignments
		possibleAssignments = possibleValues board unassignedRowColumn
		unassignedRowColumn = toRowColumn unassignedIndex
		unassignedIndex = fromJust $ elemIndex 0 board

demo :: [Int]
demo = [2,0,0,0,8,0,3,0,0,
       0,6,0,0,7,0,0,8,4,
       0,3,0,5,0,0,2,0,9,
       0,0,0,1,0,5,4,0,8,
       0,0,0,0,0,0,0,0,0,
       4,0,2,7,0,6,0,0,0,
       3,0,1,0,0,7,0,4,0,
       7,2,0,0,4,0,0,6,0,
       0,0,4,0,1,0,0,0,3]
</pre>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/antimatroid.wordpress.com/712/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/antimatroid.wordpress.com/712/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/antimatroid.wordpress.com/712/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/antimatroid.wordpress.com/712/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/antimatroid.wordpress.com/712/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/antimatroid.wordpress.com/712/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/antimatroid.wordpress.com/712/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/antimatroid.wordpress.com/712/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/antimatroid.wordpress.com/712/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/antimatroid.wordpress.com/712/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=antimatroid.wordpress.com&blog=4448583&post=712&subd=antimatroid&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://antimatroid.wordpress.com/2009/06/01/sudoku-solver-in-haskell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/62c32c6293d483fc7e1d545c4b9a0ac3?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">lewellen</media:title>
		</media:content>
	</item>
		<item>
		<title>Sudoku Solver in C# using Lambda Expressions</title>
		<link>http://antimatroid.wordpress.com/2009/05/01/sudoku-solver-in-c-using-lambda-expressions/</link>
		<comments>http://antimatroid.wordpress.com/2009/05/01/sudoku-solver-in-c-using-lambda-expressions/#comments</comments>
		<pubDate>Fri, 01 May 2009 07:00:31 +0000</pubDate>
		<dc:creator>lewellen</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Lambda Expressions]]></category>
		<category><![CDATA[Sudoku]]></category>

		<guid isPermaLink="false">http://antimatroid.wordpress.com/?p=612</guid>
		<description><![CDATA[Seems that everywhere you look someone has a Sudoku Solver that they want to showcase, well, I&#8217;m no different so I figured I&#8217;d post my take on the subject. Microsoft has introduced/included/borrowed a number of functional programming features into the latest version of C# (3.0) that have made it easier for developers to write better, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=antimatroid.wordpress.com&blog=4448583&post=612&subd=antimatroid&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Seems that everywhere you look someone has a Sudoku Solver that they want to showcase, well, I&#8217;m no different so I figured I&#8217;d post my take on the subject. Microsoft has introduced/included/borrowed a number of functional programming features into the latest version of C# (3.0) that have made it easier for developers to write better, cleaner code. One of those features continues the trend of improving  anonymous methods, which extend delegates which extend interfaces now known as Lambda expressions. E.g., the following are all the same for the expression <img src='http://l.wordpress.com/latex.php?latex=%5Clambda+x+.+x+%2A+x&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\lambda x . x * x' title='\lambda x . x * x' class='latex' />: </p>
<pre class="brush: csharp;">
Func&lt;int, int&gt; square = (x) =&gt; x * x;
</pre>
<pre class="brush: csharp;">
Func&lt;int, int&gt; square = new Func&lt;int, int&gt;(delegate(int x) { return x * x; });
</pre>
<pre class="brush: csharp;">
public interface Func&lt;T, R&gt; {
    R Evaluate(T x);
}

public class Square : Func&lt;int, int&gt; {
    public int Evaluate(int x) {
        return x*x;
    }
}

...

Func&lt;int,int&gt; square = new Square();
</pre>
<p>Given that level of expressive power, I thought I would approach this implementation using as many lambda expressions as possible to see how concise and easy to follow an implementation I could create. </p>
<p>To start off, the solver will assume that the board will be passed in as a 81 character array containing digits 0-9. Zero shall represent an unassigned cell. </p>
<p>The core loop is pretty simple: Start with the initial board on a stack, in a loop take the first board off the stack and check if it is valid. A board is said to be valid if for every row, column and region each structure contains one and only one instance of the digits 1-9. If the board is not valid, no further work should be done.</p>
<p>Next we need to check if the board is solved. If it is not, then we need to explore the possible boards that can be derived from that board. To do so, we will need to find the first possible cell that is unassigned and push on to the the stack a derived board using the possible values that can be assigned to the identified cell.</p>
<p>Once the loop finally exits, print out the solved board.</p>
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;

namespace Sudoku {
    public class Program {
        static public void Main(string[] args) {
            string input = &quot;200080300060070084030500209000105408000000000402706000301007040720040060004010003&quot;;
            Board inputBoard = null;
            try {
                inputBoard = new Board(input);
            } catch (InvalidInputException iie) {
                Console.WriteLine(iie.InvalidInput);
                return;
            }

            Stack boards = new Stack();
            boards.Push(inputBoard);
            Board board = null;
            do {
                board = boards.Pop();
                if (!board.Valid)
                    continue;
                if (!board.Solved)
                    board.FirstAvailable((r, c) =&gt;
                        board.PossibleValuesAt(r, c, (v) =&gt;
                            boards.Push(board.DeriveUsing(r, c, v))
                        )
                    );
            } while (boards.Count &gt; 0 &amp;&amp; !board.Solved);
            Console.WriteLine(board);
        }
    }
}
</pre>
<p>I&#8217;m going to start with the private member methods since they form the basic grammar that I will use to implement the public member methods and properties.</p>
<p>The first thing you&#8217;ll notice is the private class Structure; it is a simple pair class that contains two member properties for accessing a function that iterates over all possible structures and a function that iterates over all the cells in a specific structure. </p>
<p>The private constructor instantiates a private member array containing the function pointers that enumerate over Rows, Column and Regions. </p>
<p>assertStructure method which iterates over every instance of a structure in the table, and verifies that one and only one instance of the digits 1-9 exist in that structure instance. </p>
<p>indexInStructure iterates over all of the indices of a structure- in this case, 0-8.</p>
<pre class="brush: csharp;">
using System;
using System.Text;

namespace Sudoku {
    public partial class Board {
        private class Struct {
            public Action&lt;Action&lt;int&gt;&gt; In { get; set; }
            public Action&lt;int, Action&lt;int&gt;&gt; ForValues { get; set; }
            public Struct(Action&lt;Action&lt;int&gt;&gt; _in, Action&lt;int, Action&lt;int&gt;&gt; forValues) {
                In = _in; ForValues = forValues;
            }
        }

        private Struct[] structures;

        private Board(int[] board) {
            this.board = board;
            structures = new Struct[] {
                new Struct(Rows, ValuesInRow), new Struct(Columns, ValuesInColumn),
                new Struct(Regions, ValuesInRegion)
            };
        }

        private bool assertStructure(Action&lt;Action&lt;int&gt;&gt; structure, Action&lt;int, Action&lt;int&gt;&gt;
            valuesInStructure) {
            bool asserted = true;
            structure((x) =&gt; {
                int[] used = new int[10];
                valuesInStructure(x, (y) =&gt; used[y]++);
                used[0] = 0;
                asserted &amp;= forAllValues((v) =&gt; v &lt; 2, used);
            });
            return asserted;
        }

        private void indexInStructure(Action&lt;int&gt; actOnIndex) {
            indexInStructure((n) =&gt; true, actOnIndex);
        }

        private void indexInStructure(Predicate&lt;int&gt; p, Action&lt;int&gt; actOnIndex) {
            indexFromToWhere(0, 9, p, actOnIndex, false);
        }
</pre>
<p>The forAllValues method is simply a way of writing the predicate <img src='http://l.wordpress.com/latex.php?latex=%28%5Cforall+x%29+Px&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='(\forall x) Px' title='(\forall x) Px' class='latex' />  applied to members of the universe of discourse (the array that was passed in).</p>
<p>indexFromToWhere is a simple wrapper around a common for loop with filtering and the option to break after the first object to pass through the filter is found.</p>
<pre class="brush: csharp;">
        private bool forAllValues(Predicate f, T[] A) {
            bool held = true;
            for (int n = 0; n &lt; A.Length &amp;&amp; held; n++)
                held &amp;= f(A[n]);
            return held;
        }

        private void indexFromToWhere(int min, int max, Predicate&lt;int&gt; p, Action&lt;int&gt; actOnIndex,
            bool breakAfterFirst) {
            for (int n = min; n &lt; max; n++)
                if (p(n)) {
                    actOnIndex(n);
                    if (breakAfterFirst)
                        break;
                }
        }
</pre>
<p>The following methods are all related to working with the board representation. I choose to implement the board as an integer array. The at method maps a logical row and column to a row order array value within board. Each of the different indexInBoard methods allows for iterating over the indices of the board.</p>
<pre class="brush: csharp;">
        private int[] board;

        private int at(int row, int col) {
            return row * 9 + col;
        }

        private void indexInBoard(Action&lt;int&gt; actOnIndex) {
            indexInBoard((n) =&gt; true, actOnIndex);
        }

        private void indexInBoard(Predicate&lt;int&gt; p, Action&lt;int&gt; actOnIndex) {
            indexInBoard(p, actOnIndex, false);
        }

        private void indexInBoard(Predicate&lt;int&gt; p, Action&lt;int&gt; actOnIndex, bool breakAfterFirst) {
            indexFromToWhere(0, board.Length, p, actOnIndex, breakAfterFirst);
        }
    }
}
</pre>
<p>The first set of public member methods and properties we can look at are for managing the state of the board. The board is only Solved if each index is assigned. The board is only Valid if every structure in the board is asserted to be true. The constructor checks the input to make sure it is valid, delegates the some work to the private constructor and loads the input string in to the integer array.</p>
<pre class="brush: csharp;">
using System;
using System.Text;

namespace Sudoku {
    public partial class Board {
        public bool Solved {
            get {
                return forAllValues((x) =&gt; x &gt; 0, board);
            }
        }
        public bool Valid {
            get {
                return forAllValues((s) =&gt; assertStructure(s.In, s.ForValues), structures);
            }
        }

        public Board(string input) : this (new int[81]) {
            if (string.IsNullOrEmpty(input))
                throw new InvalidInputException(InvalidInput.Empty);
            if (input.Length != 81)
                throw new InvalidInputException(InvalidInput.Length);
            for (int n = 0; n  board[n] = input[n] - '0');
        }

        override public string ToString() {
            StringBuilder S = new StringBuilder(board.Length);
            indexInBoard((n) =&gt; S.Append((char)('0' + board[n])));
            return S.ToString();
        }
</pre>
<p>Next, we need a way to operate on each of the structures in the board. Each row from top to bottom, each column from left to right and each region from top left to bottom right (zig-zag) will be assigned an index from 0-8 respectively.</p>
<pre class="brush: csharp;">
        public void Columns(Action&lt;int&gt; actOnColumn) {
            indexInStructure(actOnColumn);
        }

        public void Regions(Action&lt;int&gt; actOnRegion) {
            indexInStructure(actOnRegion);
        }

        public void Rows(Action&lt;int&gt; actOnRow) {
            indexInStructure(actOnRow);
        }
</pre>
<p>It is easy to then iterate the cells in a given structure. The values in a column are simply a trip down the Rows and we only want to act when the value is defined. The values in a row are just as easy by traveling across the Columns and acting when the value is defined. Iterating over the values in the region is a little more involved, but nonetheless just as easy to follow- map the region to the appropriate reference row and column and then iterate over the 3&#215;3 grid and act only when the value is defined.</p>
<pre class="brush: csharp;">
        public void ValuesInColumn(int column, Action&lt;int&gt; actOnValue) {
            Rows((r) =&gt; {
                int value = board[at(r, column)];
                if (value &gt; 0)
                    actOnValue(value);
            });
        }

        public void ValuesInRegion(int region, Action&lt;int&gt; actOnValue) {
            int row = (region / 3) * 3;
            int column = (region % 3) * 3;
            int value = 0;
            for (int r = 0; r &lt; 3; r++)
                for (int c = 0; c  0)
                        actOnValue(value);
                }
        }

        public void ValuesInRow(int row, Action&lt;int&gt; actOnValue) {
            Columns((c) =&gt; {
                int value = board[at(row, c)];
                if (value &gt; 0)
                    actOnValue(value);
            });
        }
</pre>
<p>Finally, we have the interesting methods used in the main loop. DeriveUsing will copy the board into a cloned integer array and then assign the derived at row and column with the value supplied. The newly derived board is then returned. </p>
<p>FirstAvailable iterates over all the indices of the board until it finds an unassigned value and then it acts upon the reference row and column.</p>
<p>PossibleValuesAt goes and collects a list of possible values by first collecting the values used in the row, column and region that the reference row and column reside within, then each value not found is acted upon.</p>
<pre class="brush: csharp;">
        public Board DeriveUsing(int row, int colum, int withValue) {
            int[] derived = new int[81];
            indexInBoard((n) =&gt; derived[n] = board[n]);
            derived[at(row, colum)] = withValue;
            return new Board(derived);
        }

        public void FirstAvailable(Action&lt;int, int&gt; actOnRowAndColumn) {
            indexInBoard((n) =&gt;
                board[n] == 0, (n) =&gt; actOnRowAndColumn(n / 9, n % 9), true);
        }

        public void PossibleValuesAt(int row, int column, Action&lt;int&gt; actOnPossibleValue) {
            bool[] used = new bool[10];
            ValuesInRow(row, (x) =&gt; used[x] = true);
            ValuesInColumn(column, (x) =&gt; used[x] = true);
            ValuesInRegion((row / 3) * 3 + (column / 3), (x) =&gt; used[x] = true);
            indexFromToWhere(1, used.Length, (n) =&gt; !used[n], actOnPossibleValue, false);
        }
    }
}
</pre>
<p>Having approached this implementation as I did, I found some interesting bugs that I hadn&#8217;t come across before and I figure I&#8217;ll close with one that caught me off guard. I had spent an hour writing all my code and figured I&#8217;d run it to see what kind of output I got. To my surprise I got an immediate StackOverflowExeception. So I spent and an additional 10 minutes debugging and found the following offending code. Take a look at it and see if you can see what&#8217;s wrong with it before reading on.</p>
<pre class="brush: csharp;">
public void act(Func&lt;int,int&gt; assign){
    act((n) =&gt; board[n] = assign(n));
}

public void act(Action&lt;int&gt; actOn) {
    for(int n = 0; n &lt; board.Length; n++)
      actOn(n);
}
</pre>
<p>After a minute I had my ah-ha moment (as I&#8217;m sure have as well) and remembered that the assignment operator returns the value of the assignment so the compiler was turning (n) =&gt; board[n] = assign(n), into Func&lt;int, int&gt; instead of Action&lt;int&gt; as I had hoped. To fix the bug, I had to do the following to get the compiler to pick the statement up as Action&lt;int&gt;.</p>
<pre class="brush: csharp;">
public void act(Func&lt;int,int&gt; assign) {
    for(int n = 0; n &lt; board.Length; n++)
        act((n) =&gt; { board[n] = assign(n); });
}
</pre>
<p>Having made the change, I tested my input string and out printed the solution immediately. I decided against writing similar function overloading in the final implementation to prevent any unintended bugs.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/antimatroid.wordpress.com/612/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/antimatroid.wordpress.com/612/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/antimatroid.wordpress.com/612/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/antimatroid.wordpress.com/612/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/antimatroid.wordpress.com/612/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/antimatroid.wordpress.com/612/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/antimatroid.wordpress.com/612/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/antimatroid.wordpress.com/612/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/antimatroid.wordpress.com/612/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/antimatroid.wordpress.com/612/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=antimatroid.wordpress.com&blog=4448583&post=612&subd=antimatroid&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://antimatroid.wordpress.com/2009/05/01/sudoku-solver-in-c-using-lambda-expressions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/62c32c6293d483fc7e1d545c4b9a0ac3?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">lewellen</media:title>
		</media:content>
	</item>
		<item>
		<title>Integer Factorization by Dynamic Programming with Number Theoretic Applications</title>
		<link>http://antimatroid.wordpress.com/2009/04/01/integer-factorization-by-dynamic-programming-with-number-theoretic-applications/</link>
		<comments>http://antimatroid.wordpress.com/2009/04/01/integer-factorization-by-dynamic-programming-with-number-theoretic-applications/#comments</comments>
		<pubDate>Wed, 01 Apr 2009 07:00:45 +0000</pubDate>
		<dc:creator>lewellen</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[C# 2.0]]></category>
		<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[Integer Factorization]]></category>
		<category><![CDATA[Number Theory]]></category>

		<guid isPermaLink="false">http://antimatroid.wordpress.com/?p=615</guid>
		<description><![CDATA[Having been a participant of a number of mathematical programming competitions over the years, I&#8217;ve had to find a number of efficient ways of implementing many common Number Theoretic Functions. In this write up, I&#8217;m going to go over a method I&#8217;ve found useful for easily factoring numbers using a sieving method, go over some [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=antimatroid.wordpress.com&blog=4448583&post=615&subd=antimatroid&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Having been a participant of a number of mathematical programming competitions over the years, I&#8217;ve had to find a number of efficient ways of implementing many common Number Theoretic Functions. In this write up, I&#8217;m going to go over a method I&#8217;ve found useful for easily factoring numbers using a sieving method, go over some the implementation of a few number theory functions along with time complexity analysis of each. The cornerstone to many of these implementations relies on the ability to quickly factor integers and find primes.</p>
<p>One of the most popular methods of for finding primes is the <a target="blank" href="http://mathworld.wolfram.com/SieveofEratosthenes.html">Sieve of Eratosthenes</a>. The algorithm starts by populating a table with every positive integer from 2 to a ceiling value. Then find the first integer not yet crossed off, in the case 2, and eliminate every multiple of 2 from the table then return to 2 and find the next positive integer not yet crossed off and repeat the procedure until the end of the table is reached. The method is fine and all, but a lot of really great information is lost in that computation. Here is a sample implementation:</p>
<pre class="brush: csharp;">
bool[] isPrime = new bool[400];
for (uint n = 2; n &lt; isPrime.Length; n++)
    isPrime[n] = true;
for (uint n = 2; n &lt; isPrime.Length; n++)
    if (isPrime[n])
        for (uint m = 2, c = 0; (c = m * n) &lt; isPrime.Length; m++)
            isPrime[c] = false;
</pre>
<p>On the other hand, say we approach sieve a little differently. Create an empty table as large as the ceiling value. Start at 2 and for every multiple of 2, create a record that has two parts: 2 and half of the multiple. Return to 2 and find the next integer in the table that has yet to be recorded, in this case 3. For every multiple of 3, create a record that has two parts: 3 and third of the multiple (only if the multiple was not previously recorded. E.g., 6 because 2 previously recorded the record). Return to 3 and find the next integer in the table that has yet to be recorded so on and so forth until every integer in the table has been recorded.</p>
<p>The following graphic demonstrates this process for a ceiling values of 25. If we wish to factor 16, we go to 16&#8217;s record (2, 8), follow to 8&#8217;s record (2,4), again follow 4&#8217;s record (2, 2) and finally 2&#8217;s record (2, &lambda;). Thus the prime factorization of 16 is 2, 2, 2, 2.</p>
<p><a href="http://antimatroid.files.wordpress.com/2009/05/factor_table_polar.png"><img src="http://antimatroid.files.wordpress.com/2009/05/factor_table_polar.png?w=700&#038;h=760" alt="factor_table_polar" title="factor_table_polar" width="700" height="760" class="aligncenter size-full wp-image-622" /></a></p>
<p>It should be apparent that this algorithm is a simple dynamic programming solution that yields two major results: </p>
<ol>
<li>We have factored every positive integer up to a ceiling value.</li>
<li>We have found every positive prime integer up to a ceiling value.</li>
</ol>
<p>And one major draw back</p>
<ol>
<li>Uses a lot of memory as a trade off for speed.</li>
</ol>
<p>Let&#8217;s get into the C# implementation. To start off, we need a record class that&#8217;ll store the information about the first prime that divides an entry and the composite to jump to if the record corresponds to a composite. </p>
<pre class="brush: csharp;">
public class Record {
    public uint Prime {get; set;}
    public uint? JumpTo {get; set;}
}
</pre>
<p>We&#8217;ll have a class called NumberTheory and assume that it has the following structure. If you want, you could make this a Singleton class but I felt it was unnecessary for the scope of this write up.</p>
<pre class="brush: csharp;">
public class NumberTheory {
    private Record[] table;

    ...
}
</pre>
<p>It makes sense to put the core algorithm in the constructor and then have member methods for each of the functions we&#8217;d like to have. It should be assumed that for the lifetime of the class that the largest value ever called on the methods will be N otherwise an exception should be thrown by the methods (omitted here for brevity).</p>
<pre class="brush: csharp;">
public NumberTheory(uint N){
    uint c = 0;
    table = new Record[N+1];
    for(uint n = 2; n &lt; table.Length; n++) {
        if(table[n] != null)
            continue;
        table[n] = new Record() { Prime = n };
        for(uint m = 2; (c = n * m) &lt; table.Length; m++)
            if(table[c] == null)
                table[c] = new Record() { JumpTo = m, Prime = n };
    }
}
</pre>
<p>The time complexity of the implementation can be derived using some analysis and by having some knowledge of certain identities. Starting from 2 there are N &#8211; 2 numbers to check of which 1/2 will be visited by the interior loop, starting from 3 there are N &#8211; 3 numbers to check of which 1/3 will be visited visited by the interior loop, so on and so forth leading to the following summation:<br />
<img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle+T%28n%29+%3D+%5Csum_%7Bp+%5Cle+n%7D+%5Cleft%28+%5Cfrac%7B1%7D%7Bp%7D%28n+-+p%29+%5Cright%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\displaystyle T(n) = \sum_{p \le n} \left( \frac{1}{p}(n - p) \right)' title='\displaystyle T(n) = \sum_{p \le n} \left( \frac{1}{p}(n - p) \right)' class='latex' /><br />
<img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle+T%28n%29+%3D+%5Csum_%7Bp+%5Cle+n%7D+%5Cleft%28+%5Cfrac%7Bn%7D%7Bp%7D+-+1+%5Cright%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\displaystyle T(n) = \sum_{p \le n} \left( \frac{n}{p} - 1 \right)' title='\displaystyle T(n) = \sum_{p \le n} \left( \frac{n}{p} - 1 \right)' class='latex' /></p>
<p>If we separate the summation into the harmonic series of primes (HSP) and prime counting function (aggregate 1 for every prime less than n) we get:<br />
<img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle+T%28n%29+%3D+n+%5Csum_%7Bp+%5Cle+n%7D+%5Cleft%28+%5Cfrac%7B1%7D%7Bp%7D+%5Cright%29+-+%5Cpi%28n%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\displaystyle T(n) = n \sum_{p \le n} \left( \frac{1}{p} \right) - \pi(n)' title='\displaystyle T(n) = n \sum_{p \le n} \left( \frac{1}{p} \right) - \pi(n)' class='latex' /></p>
<p>Asymptotically, the HSP tends towards <img src='http://l.wordpress.com/latex.php?latex=%5Cln+%5Cln+n&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\ln \ln n' title='\ln \ln n' class='latex' /> and <img src='http://l.wordpress.com/latex.php?latex=%5Cpi%28n%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\pi(n)' title='\pi(n)' class='latex' /> towards <img src='http://l.wordpress.com/latex.php?latex=%5Cfrac%7Bn%7D%7B%5Cln+n%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\frac{n}{\ln n}' title='\frac{n}{\ln n}' class='latex' />.<br />
<img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle+T%28n%29+%3D+n+%5Cleft%28+%5Cln+%5Cln+n+%5Cright%29+-+%5Cpi%28n%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\displaystyle T(n) = n \left( \ln \ln n \right) - \pi(n)' title='\displaystyle T(n) = n \left( \ln \ln n \right) - \pi(n)' class='latex' /><br />
<img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle+T%28n%29+%3D+n+%5Cleft%28+%5Cln+%5Cln+n+%5Cright%29+-+%5Cfrac%7Bn%7D%7B%5Cln+n%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\displaystyle T(n) = n \left( \ln \ln n \right) - \frac{n}{\ln n}' title='\displaystyle T(n) = n \left( \ln \ln n \right) - \frac{n}{\ln n}' class='latex' /><br />
<img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle+T%28n%29+%3D+n+%5Cfrac%7B+%5Cln+n+%5Ccdot+%5Cln+%5Cln%28n%29+-+1%7D%7B%5Cln+n%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\displaystyle T(n) = n \frac{ \ln n \cdot \ln \ln(n) - 1}{\ln n}' title='\displaystyle T(n) = n \frac{ \ln n \cdot \ln \ln(n) - 1}{\ln n}' class='latex' /></p>
<p>Giving us our final asymptotic time complexity of <img src='http://l.wordpress.com/latex.php?latex=O%28n+%5Cln+%5Cln+n%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='O(n \ln \ln n)' title='O(n \ln \ln n)' class='latex' />.</p>
<p>The first member method we&#8217;ll implement is a trivial check to see if a given number is prime by checking the table&#8217;s Record&#8217;s JumpTo property for null.</p>
<pre class="brush: csharp;">
public bool IsPrime(uint N){
    return !table[N].JumpTo.HasValue;
}
</pre>
<p>The time complexity here is a simple <img src='http://l.wordpress.com/latex.php?latex=O%281%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='O(1)' title='O(1)' class='latex' />.</p>
<p>From IsPrime, we can easily implement a function that will get every single prime up to a given value by iterating over the table.</p>
<pre class="brush: csharp;">
public void PrimesLessThan(uint value, Action&lt;uint&gt; actOnPrime) {
    for(int n = 2; n &lt; value; n++)
	if(IsPrime(n))
		actOnPrime(n);
}
</pre>
<p>We can get the prime counting function <img src='http://l.wordpress.com/latex.php?latex=%5Cpi%28n%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\pi(n)' title='\pi(n)' class='latex' /> but utilizing the PrimeLessThan function.</p>
<pre class="brush: csharp;">
public uint CountPrimes(uint n) {
	uint count = 0;
	PrimesLessThan(n, (p) =&gt; {count++;});
	return count;
}
</pre>
<p>Here the time complexity is the same as PrimesLessThan: <img src='http://l.wordpress.com/latex.php?latex=O%28n%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='O(n)' title='O(n)' class='latex' />.</p>
<p>We can get the prime factorization of a composite easily. To do so, we simply iterate over the records until we reach a Record with no JumpTo value.</p>
<pre class="brush: csharp;">
public void PrimeFactorsOf(uint composite, Action actOnFactor) {
    Record temp = table[composite];
    while(temp != null) {
        actOnFactor(temp.Prime);
        if(temp.JumpTo.HasValue)
            temp = table[temp.JumpTo.Value];
        else
            temp = null;
    }
}
</pre>
<p>The time complexity of this implementation relies on the the prime omega function <img src='http://l.wordpress.com/latex.php?latex=%5COmega%28n%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\Omega(n)' title='\Omega(n)' class='latex' /> which is the number of prime factors (not necessarily distinct) of n. The function tends to <img src='http://l.wordpress.com/latex.php?latex=O%28+%5Cln+%5Cln+n%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='O( \ln \ln n)' title='O( \ln \ln n)' class='latex' />.</p>
<p>From PrimeFactorsOf, we can also easily implement Euler&#8217;s Totient Function <img src='http://l.wordpress.com/latex.php?latex=%5Cphi%28n%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\phi(n)' title='\phi(n)' class='latex' />- the function tells us how many positive integers less than n are coprime to n. It is defined as:<br />
<img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle+%5Cphi%28n%29+%3D+n+%5Cprod_%7Bp%7Cn%7D+%5Cleft%28+1+-+%5Cfrac%7B1%7D%7Bp%7D+%5Cright%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\displaystyle \phi(n) = n \prod_{p|n} \left( 1 - \frac{1}{p} \right)' title='\displaystyle \phi(n) = n \prod_{p|n} \left( 1 - \frac{1}{p} \right)' class='latex' /><br />
Which essentially states that if you multiply all of the repeated prime factors of n together by all of the non-repeat prime factors &#8211; 1 of n together, you will have the result of <img src='http://l.wordpress.com/latex.php?latex=%5Cphi%28n%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\phi(n)' title='\phi(n)' class='latex' />.</p>
<pre class="brush: csharp;">
public uint EulerTotient(uint n){
    uint phi = 1, last = 0;
    PrimeFactorsOf(n, (p) =&gt; {
        if(p != last) {
            phi *= p - 1;
            last = p;
        } else {
            phi *= p;
        }
    });
    return phi;
}
</pre>
<p>A similar function known as the Dedekind <img src='http://l.wordpress.com/latex.php?latex=%5Cpsi%28n%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\psi(n)' title='\psi(n)' class='latex' /> Function defined as<br />
<img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle+%5Cpsi%28n%29+%3D+n+%5Cprod_%7Bp%7Cn%7D+%5Cleft+%28+1+%2B+%5Cfrac%7B1%7D%7Bp%7D+%5Cright+%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\displaystyle \psi(n) = n \prod_{p|n} \left ( 1 + \frac{1}{p} \right )' title='\displaystyle \psi(n) = n \prod_{p|n} \left ( 1 + \frac{1}{p} \right )' class='latex' /><br />
can be implemented in a similar way as <img src='http://l.wordpress.com/latex.php?latex=%5Cphi%28n%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\phi(n)' title='\phi(n)' class='latex' />:</p>
<pre class="brush: csharp;">
public uint DedekindPsi(uint n){
    uint phi = 1, last = 0;
    PrimeFactorsOf(n, (p) =&gt; {
        if(p != last) {
            phi *= p + 1;
            last = p;
        } else {
            phi *= p;
        }
    });
    return phi;
}
</pre>
<p>The Von Mangoldt Function <img src='http://l.wordpress.com/latex.php?latex=%5CLambda%28n%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\Lambda(n)' title='\Lambda(n)' class='latex' /> is another interesting function, unfortunately I haven&#8217;t had a chance to use it, but it is trivial to implement so I will include it here for completeness. It is defined as<br />
<img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle+%5CLambda+%28n%29+%3D+%5Cbegin%7Bcases%7D+%5Cln%7Bp%7D+%26+%5Ctext+%7Bif+n+%3D+prime+to+some+positive+integer+power%7D+%5C%5C+0+%26+%5Ctext%7Botherwise%7D+%5Cend%7Bcases%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\displaystyle \Lambda (n) = \begin{cases} \ln{p} &amp; \text {if n = prime to some positive integer power} \\ 0 &amp; \text{otherwise} \end{cases}' title='\displaystyle \Lambda (n) = \begin{cases} \ln{p} &amp; \text {if n = prime to some positive integer power} \\ 0 &amp; \text{otherwise} \end{cases}' class='latex' /></p>
<pre class="brush: csharp;">
public double VonMangoldt(uint n){
    uint P = 0;
    PrimeFactorsOf(n, (p) =&gt; {
        if(P == 0) {
            P = p;
        } else if (P != p) {
            P = 1;
        }
    });
    return Math.Log(P);
}
</pre>
<p>The M&ouml;bius Function <img src='http://l.wordpress.com/latex.php?latex=%5Cmu%28n%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\mu(n)' title='\mu(n)' class='latex' /> is a handy little function for determining if a number is square free or not (among many more interesting things). It is defined as:<br />
<img src='http://l.wordpress.com/latex.php?latex=+%5Cdisplaystyle+%5Cmu%28n%29+%3D+%5Cbegin%7Bcases%7D+0+%26+%5Ctext%7Bif+n+has+one+or+more+replicated+factors%7D+%5C%5C+1+%26+%5Ctext%7Bif+n+%3D+1%7D+%5C%5C+%28-1%29%5E%7Bk%7D+%26+%5Ctext%7Bif+n+is+a+product+of+k+distinct+primes%7D+%5Cend%7Bcases%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt=' \displaystyle \mu(n) = \begin{cases} 0 &amp; \text{if n has one or more replicated factors} \\ 1 &amp; \text{if n = 1} \\ (-1)^{k} &amp; \text{if n is a product of k distinct primes} \end{cases}' title=' \displaystyle \mu(n) = \begin{cases} 0 &amp; \text{if n has one or more replicated factors} \\ 1 &amp; \text{if n = 1} \\ (-1)^{k} &amp; \text{if n is a product of k distinct primes} \end{cases}' class='latex' /></p>
<pre class="brush: csharp;">
public int MoebiusFunction(uint N){
    if(N == 1)
        return 1;
    bool distinct = true;
    uint last = 0, k = 0;
    PrimeFactorsOf(N, (p) =&gt; {
        if(p == last) {
            distinct = false;
        } else {
            k++;
            last = p;
        }
    });

    if(distinct)
        return ((k &amp; 1) == 0) ? 1 : -1;
    return 0;
}
</pre>
<p>Since EulerTotient, DedekindPsi, VonMangoldt and Moebius each use PrimeFactorsOf without any additional lifting, their time complexities are the same as PrimeFactorsOf &#8211; <img src='http://l.wordpress.com/latex.php?latex=O%28%5Cln+%5Cln+n%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='O(\ln \ln n)' title='O(\ln \ln n)' class='latex' />.</p>
<p>The last function I&#8217;ll implement is the Mertens Function <img src='http://l.wordpress.com/latex.php?latex=M%28n%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='M(n)' title='M(n)' class='latex' /> which is simply defined as <img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle+M%28n%29+%3D+%5Csum_%7Bk+%3D+1%7D%5E%7Bn%7D+%5Cmu%28k%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\displaystyle M(n) = \sum_{k = 1}^{n} \mu(k)' title='\displaystyle M(n) = \sum_{k = 1}^{n} \mu(k)' class='latex' />:</p>
<pre class="brush: csharp;">
public int Mertens(uint n){
    int m = 0;
    for(uint k = 1; k &lt;= n; k++)
        m += MoebiusFunction(k);
    return m;
}
</pre>
<p>The implementation&#8217;s time complexity is simply <img src='http://l.wordpress.com/latex.php?latex=O%28n+%5Cln+%5Cln+n%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='O(n \ln \ln n)' title='O(n \ln \ln n)' class='latex' />.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/antimatroid.wordpress.com/615/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/antimatroid.wordpress.com/615/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/antimatroid.wordpress.com/615/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/antimatroid.wordpress.com/615/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/antimatroid.wordpress.com/615/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/antimatroid.wordpress.com/615/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/antimatroid.wordpress.com/615/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/antimatroid.wordpress.com/615/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/antimatroid.wordpress.com/615/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/antimatroid.wordpress.com/615/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=antimatroid.wordpress.com&blog=4448583&post=615&subd=antimatroid&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://antimatroid.wordpress.com/2009/04/01/integer-factorization-by-dynamic-programming-with-number-theoretic-applications/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/62c32c6293d483fc7e1d545c4b9a0ac3?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">lewellen</media:title>
		</media:content>

		<media:content url="http://antimatroid.files.wordpress.com/2009/05/factor_table_polar.png" medium="image">
			<media:title type="html">factor_table_polar</media:title>
		</media:content>
	</item>
		<item>
		<title>Generalized Interpreter Framework in C#</title>
		<link>http://antimatroid.wordpress.com/2009/03/01/generalized-interpreter-framework-in-c/</link>
		<comments>http://antimatroid.wordpress.com/2009/03/01/generalized-interpreter-framework-in-c/#comments</comments>
		<pubDate>Sun, 01 Mar 2009 07:00:49 +0000</pubDate>
		<dc:creator>lewellen</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[C# 2.0]]></category>
		<category><![CDATA[Interpreter Design]]></category>
		<category><![CDATA[Sentential Logic]]></category>

		<guid isPermaLink="false">http://antimatroid.wordpress.com/?p=519</guid>
		<description><![CDATA[Introduction
Like most Computer Science graduates, I had taken a Programming Languages course during college in which we built a compiler and studied the consequences of our design decisions. I had also taken a course in symbolic logic- particularly, looking at the sentential and predicate logic. Lately, I had been thinking about these two courses and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=antimatroid.wordpress.com&blog=4448583&post=519&subd=antimatroid&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h2>Introduction</h2>
<p>Like most Computer Science graduates, I had taken a Programming Languages course during college in which we built a compiler and studied the consequences of our design decisions. I had also taken a course in symbolic logic- particularly, looking at the sentential and predicate logic. Lately, I had been thinking about these two courses and thought it would be interesting to write an interpreter that would take in a sentence valid under sentential logic and output the resulting truth table.</p>
<p>After looking at what I had built, it became apparent that I could generalize my solution into a flexible framework where I could easily create a new interpreter for a desired (albeit simple) formal grammar and produce the desired outputs that other applications could then use for whatever purpose. The following is an overview of this framework and an example implementation for generating truth tables for sentences valid under sentential logic.</p>
<h2>Framework</h2>
<h3>Specification</h3>
<p>An Interpreter takes a string and produces an object hierarchy that a client can perform functions upon. The Interpreter does so by following the rules of a grammar that the string is assumed (although not garaunteed) to be valid under. The Interpreter will only be valid for context-free-grammars (CFG). A CFG consists of Terminals and Nonterminals. A Terminal is a character or sequence of characters that terminate a definition. A Nonterminal is a rule that defines the relationships between other Nonterminals and Terminals. </p>
<h3>Design</h3>
<p><img src="http://antimatroid.files.wordpress.com/2009/03/interpreter_components.png?w=210&#038;h=360" alt="interpreter_components" title="interpreter_components" width="210" height="360" class="alignright size-full wp-image-564" /></p>
<p>Interpreter designs differs from traditional compiler design, in that only the so-called front-end is implemented. There are three principal components involved in this process: Tokenizer, Parser and Semantic Analyzer. </p>
<p>A Tokenizer takes a string of characters and returns a collection of Tokens, where each Token is a tuple containing the accepted substring and meta data describing what the substring represents. Tokens are identified by looking for Terminals in the input string. </p>
<p>The Parser then builds (formally) a concrete syntax tree (informally a syntax tree) following the rules defined by the grammar. This is done by looking for Nonterminals in the collection of Tokens.   </p>
<p>Finally, the Semantic Analyzer builds (formally) an abstract syntax tree (informally a semantic tree) by ignoring the syntax in the parse tree and constructing the appropriate tree for performing functions upon. </p>
<p>In the event of an exception, the Interpreter will write the details of the exception to a text writer (e.g., Console.Error) provided by the client of the Interpreter.</p>
<p>Exceptions are to be thrown under the following conditions:</p>
<ul>
<li>The input string is null or empty, or none of the Terminals are able to accept a character in the input string.</li>
<li>None of the Nonterminals are able to accept a set of tokens, or the number of tokens is deficient for the Nonterminals to identify a match.</li>
</ul>
<h3>Implementation</h3>
<p><a href="http://antimatroid.files.wordpress.com/2009/03/interpreter_uml.png"><img src="http://antimatroid.files.wordpress.com/2009/03/interpreter_uml.png?w=700&#038;h=680" alt="interpreter_uml" title="interpreter_uml" width="700" height="680" class="aligncenter size-full wp-image-524" /></a></p>
<pre class="brush: csharp;">
abstract public class Tokenizer&lt;T&gt; {
    protected TerminalList&lt;T&gt; Terminals { get; private set; }

    public Tokenizer() {
        Terminals = new TerminalList&lt;T&gt;();
        loadTerminals();
    }

    public TokenList&lt;T&gt; Tokenize(string input) {
        if (string.IsNullOrEmpty(input))
            throw new UnexpectedEndOfInputException();

        TokenList&lt;T&gt; tokens = new TokenList&lt;T&gt;();
        Token&lt;T&gt; candiate;

        for (int n = 0; n &lt; input.Length; n++) {
            if (char.IsWhiteSpace(input[n]))
                continue;

            if (!terminalExists(input, n, out candiate))
                throw new UnexpectedInputException(n);

            tokens.Add(candiate);
            n += candiate.Lexeme.Length - 1;
        }

        return tokens;
    }

    private bool terminalExists(string input, int n, out Token&lt;T&gt; candiate) {
        candiate = null;
        foreach (Terminal&lt;T&gt; terminal in Terminals)
            if (terminal.Exists(input, n, out candiate))
                return true;
        return false;
    }

    abstract protected void loadTerminals();
}
</pre>
<pre class="brush: csharp;">
abstract public class Parser&lt;T, P&gt; {
    protected NonterminalList&lt;T, P&gt; Nonterminals { get; private set; }
    protected T[] FirstExpectedTokens { get; private set; }

    public Parser() {
        Nonterminals = new NonterminalList&lt;T, P&gt;();
        loadNonterminals();

        FirstExpectedTokens = new T[Nonterminals.Count];
        for (int n = 0; n &lt; Nonterminals.Count; n++)
            FirstExpectedTokens[n] = Nonterminals[n].FirstExpectedToken;
    }

    public P Parse(TokenList&lt;T&gt; tokens) {
        return Parse(tokens, 0, tokens.Count - 1);
    }

    public P Parse(TokenList&lt;T&gt; tokens, int n, int m) {
        P parsedSentence;
        foreach (Nonterminal&lt;T, P&gt; nonterminal in Nonterminals)
            if (nonterminal.Exists(tokens, n, m, out parsedSentence))
                return parsedSentence;

        throw new UnexpectedTokenException&lt;T&gt;(tokens[n], FirstExpectedTokens);
    }

    abstract protected void loadNonterminals();
}
</pre>
<pre class="brush: csharp;">
abstract public class SemanticAnalyzer&lt;P, S&gt; {
    abstract public S Analyze(P sentence);
}
</pre>
<pre class="brush: csharp;">
abstract public class Interpreter&lt;T, P, S&gt; {
    private TextWriter externalLogger;

    abstract protected Tokenizer&lt;T&gt; Tokenizer { get; }
    abstract protected Parser&lt;T, P&gt; Parser { get; }
    abstract protected SemanticAnalyzer&lt;P, S&gt; SemanticAnalyzer { get; }

    public Interpreter(TextWriter externalLogger) {
        this.externalLogger = externalLogger;
    }

    public bool Interpret(string candidateSentence, out S sentence, out TokenList&lt;T&gt; tokens) {
        sentence = default(S);
        tokens = null;

        try {
            tokens = Tokenizer.Tokenize(candidateSentence);
            sentence = SemanticAnalyzer.Analyze(Parser.Parse(tokens));

            return true;
        } catch (UnexpectedInputException uie) {
            logger(uie.Message);
            logger(&quot;'{0}'&quot;, candidateSentence);
            logger(&quot; {0}^&quot;, string.Empty.PadLeft(uie.AtIndex, '.'));

        } catch (UnexpectedEndOfInputException ueie) {
            logger(ueie.Message);
            logger(&quot;'{0}'&quot;, candidateSentence);
            logger(&quot; {0}^&quot;, string.Empty.PadLeft(candidateSentence.Length, '.'));

        } catch (UnexpectedTokenException&lt;T&gt; pe) {
            logger(pe.Message);
            logger(&quot;'{0}'&quot;, candidateSentence);
            logger(&quot; {0}^&quot;, string.Empty.PadLeft(pe.Unexpected.StartsAtIndex, '.'));
        }

        return false;
    }

    private void logger(string format, params object[] values) {
        externalLogger.WriteLine(format, values);
    }
}
</pre>
<h2>Example</h2>
<h3>Specification</h3>
<table border="0" cellspacing="0" align="right" style="margin-left:32px;margin-bottom:32px;">
<tr>
<th colspan="3">SL Backus-Naur Form (BNF)</th>
</tr>
<tr>
<td rowspan="3" valign="top">sentence</td>
<td>::=</td>
<td>sentence_letter</td>
</tr>
<tr>
<td>|</td>
<td><b>~</b> sentence</td>
</tr>
<tr>
<td>|</td>
<td><b>(</b> sentence connective sentence <b>)</b></td>
</tr>
<tr>
<td colspan="3">&nbsp;</td>
</tr>
<tr>
<td rowspan="2" valign="top">sentence_letter</td>
<td>::=</td>
<td>letter</td>
</tr>
<tr>
<td>|</td>
<td>letter number</td>
</tr>
<tr>
<td colspan="3">&nbsp;</td>
</tr>
<tr>
<td rowspan="4" valign="top">connective</td>
<td>::=</td>
<td><b>v</b></td>
</tr>
<tr>
<td>|</td>
<td><b>^</b></td>
</tr>
<tr>
<td>|</td>
<td><b>-&gt;</b></td>
</tr>
<tr>
<td>|</td>
<td><b>&lt;-&gt;</b></td>
</tr>
<tr>
<td colspan="3">&nbsp;</td>
</tr>
<tr>
<td rowspan="6" valign="top">letter</td>
<td>::=</td>
<td><b>a</b></td>
</tr>
<tr>
<td>|</td>
<td>&hellip;</td>
</tr>
<tr>
<td>|</td>
<td><b>z</b></td>
</tr>
<tr>
<td>|</td>
<td><b>A</b></td>
</tr>
<tr>
<td>|</td>
<td>&hellip;</td>
</tr>
<tr>
<td>|</td>
<td><b>Z</b></td>
</tr>
<tr>
<td colspan="3">&nbsp;</td>
</tr>
<tr>
<td rowspan="2" valign="top">number</td>
<td>::=</td>
<td>number digit</td>
</tr>
<tr>
<td>|</td>
<td>digit</td>
</tr>
<tr>
<td colspan="3">&nbsp;</td>
</tr>
<tr>
<td rowspan="3" valign="top">digit</td>
<td>::=</td>
<td><b>0</b></td>
</tr>
<tr>
<td>|</td>
<td>&hellip;</td>
</tr>
<tr>
<td>|</td>
<td><b>9</b></td>
</tr>
</table>
<p>Sentential Logic (SL) is a simple formal system that consists of two semantic elements: primitive types called Sentence Letters that may either be true or false, and expressions built upon Sentence Letters called Sentences. A Sentence Letter is any character a-z (lower or upper) followed by an optional number. Sentences are defined in terms of other sentences, the simplest is a plain Sentence Letter. Any negated  &not; sentence is also a sentence. Any two sentences connected by a conjunction &and;, disjunction &or;, material conditional &rarr; or material biconditional &harr; and enclosed by parentheses () is also a sentence under SL. No other arrangement of symbols constitutes a sentence under SL. </p>
<table align="center" style="margin-bottom:16px;">
<tr>
<th colspan="18">Connectives and negation Truth Tables</th>
</tr>
<tr>
<th>&nbsp;</th>
<th>&not;</th>
<th>&nbsp;</th>
<th>&and;</th>
<th>T</th>
<th>F</th>
<th>&nbsp;</th>
<th>&or;</th>
<th>T</th>
<th>F</th>
<th>&nbsp;</th>
<th>&rarr;</th>
<th>T</th>
<th>F</th>
<th>&nbsp;</th>
<th>&harr;</th>
<th>T</th>
<th>F</th>
</tr>
<tr>
<th>T</th>
<td>F</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>T</td>
<td>F</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>T</td>
<td>T</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>T</td>
<td>F</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>T</td>
<td>F</td>
</tr>
<tr>
<th>F</th>
<td>T</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>F</td>
<td>F</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>T</td>
<td>F</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>T</td>
<td>T</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>F</td>
<td>T</td>
</tr>
</table>
<p>A truth table has a column for each of the sentence letter that show up in a sentence and a column for the sentence. Each row is one Cartesian coordinate in the space <img src='http://l.wordpress.com/latex.php?latex=%5C%7BT%2C+F+%5C%7D%5E%7Bn%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\{T, F \}^{n}' title='\{T, F \}^{n}' class='latex' /> where n is the number of the number sentence letters. By convention, one lists the rows in order all sentence letters being true, to the last row where all sentence letters are false.</p>
<h3>Implementation</h3>
<p>TerminalSyntax and TerminalSentenceLetter are subclasses of Terminal and implement the logic for determining if a certain syntax or sentence letter exists in an input string. TerminalSyntax takes in the TokenType and string to find in the input as configuration options. If one felt inclined, one could have implemented a TerminalRegularExpression class instead of two separate classes but I felt it was unnecessary.</p>
<pre class="brush: csharp;">
public class SLTokenizer : Tokenizer&lt;TokenType&gt; {
    protected override void loadTerminals() {
        Terminals.AddRange(new Terminal&lt;TokenType&gt;[] {
            new TerminalSyntax(TokenType.Conjunction, &quot;^&quot;),
            new TerminalSyntax(TokenType.Disjunction, &quot;v&quot;),
            new TerminalSyntax(TokenType.LeftParen, &quot;(&quot;),
            new TerminalSyntax(TokenType.MaterialBiconditional, &quot;&lt;-&gt;&quot;),
            new TerminalSyntax(TokenType.MaterialConditional, &quot;-&gt;&quot;),
            new TerminalSyntax(TokenType.Negation, &quot;~&quot;),
            new TerminalSyntax(TokenType.RightParen, &quot;)&quot;),
            new TerminalSentenceLetter()
        });
    }
}
</pre>
<p>The three Nonterminal types for Connectives, Negation and Letters are subclasses of Nonterminal and implement the logic for determining if a collection of tokens matches the rules associated with each Nonterminal type.</p>
<pre class="brush: csharp;">
public class SLParser : Parser&lt;TokenType, ParsedSentence&gt; {
    protected override void loadNonterminals() {
        Nonterminals.AddRange(new Nonterminal&lt;TokenType, ParsedSentence&gt;[] {
            new NonterminalSentenceConnective(this),
            new NonterminalSentenceNegation(this),
            new NonterminalSentenceLetter()
        });
    }
}
</pre>
<p>Nothing particularly exciting here, simply mapping the parsed sentences to actual sentences that will be used by the client code. Sentence implementations have the logic for evaluating themselves.</p>
<pre class="brush: csharp;">
public class SLSemanticAnalyzer : SemanticAnalyzer&lt;ParsedSentence, Sentence&gt; {
    public override Sentence Analyze(ParsedSentence sentence) {
        ParsedSentenceLetter letter = sentence as ParsedSentenceLetter;
        if (letter != null)
            return new SentenceLetter(letter);

        ParsedSentenceUnary negation = sentence as ParsedSentenceUnary;
        if (negation != null)
            return new SentenceUnaryNegation(negation, Analyze(negation.Sentence));

        ParsedSentenceBinary connective = sentence as ParsedSentenceBinary;
        if (connective != null) {
            switch (connective.Operation.TokenType) {
                case TokenType.Conjunction:
                    return new SentenceBinaryConjunction(connective, Analyze(connective.Left), Analyze(connective.Right));
                case TokenType.Disjunction:
                    return new SentenceBinaryDisjunction(connective, Analyze(connective.Left), Analyze(connective.Right));
                case TokenType.MaterialBiconditional:
                    return new SentenceBinaryMaterialBiconditional(connective, Analyze(connective.Left), Analyze(connective.Right));
                case TokenType.MaterialConditional:
                    return new SentenceBinaryMaterialConditional(connective, Analyze(connective.Left), Analyze(connective.Right));
            }
        }

        throw new NotImplementedException();
    }
}
</pre>
<p>Nothing extra to implement in the SLInterpreter to add other than the constructor and properties.</p>
<pre class="brush: csharp;">
public class SLInterpreter : Interpreter&lt;TokenType, ParsedSentence, Sentence&gt; {
    public SLInterpreter(TextWriter externalLogger) : base(externalLogger) { 

    }

    override protected Tokenizer&lt;TokenType&gt; Tokenizer {
        get { return new SLTokenizer(); }
    }

    override protected Parser&lt;TokenType, ParsedSentence&gt; Parser {
        get { return new SLParser(); }
    }

    override protected SemanticAnalyzer&lt;ParsedSentence, Sentence&gt; SemanticAnalyzer {
        get { return new SLSemanticAnalyzer(); }
    }
}
</pre>
<p>Once all of the Interpreter code has been completed, it becomes trivial to go and implement the truth table.</p>
<pre class="brush: csharp;">
private void table(string input) {
    SLInterpreter interpreter = new SLInterpreter(Console.Out);
    TokenList&lt;TokenType&gt; tokens;
    Sentence sentence;

    if (!interpreter.Interpret(input, out sentence, out tokens))
        return;

    List&lt;Variable&gt; variables = tokens
       .Where((x) =&gt; x.TokenType == TokenType.Letter)
       .Select((x) =&gt; x.Lexeme)
       .Distinct()
       .Select((x) =&gt; new Variable(x))
       .ToList();

    foreach (Variable variable in variables)
        Console.Write(&quot;{0} &quot;, variable.Identifier);
    Console.WriteLine(&quot;| {0}&quot;, input);

    for (int n = (1 &lt;&lt; variables.Count) - 1; n &gt;= 0; n--) {
        int N = n;
        for (int m = variables.Count - 1; m &gt;= 0; m--) {
            variables[m].Value = (N &amp; 1) == 1;
            N &gt;&gt;= 1;
        }

        IDictionary&lt;Token&lt;TokenType&gt;, bool&gt; tableRow = new Dictionary&lt;Token&lt;TokenType&gt;, bool&gt;();
        sentence.Evaluate(variables, tableRow);

        int offset = 2;
        foreach (Variable variable in variables) {
            Console.Write(&quot;{0} &quot;, variable.Value ? &quot;T&quot; : &quot;F&quot;);
            offset += 1 + variable.Identifier.Length;
        }

        Console.Write(&quot;| &quot;);
        foreach (Token&lt;TokenType&gt; token in tableRow.Keys) {
            Console.CursorLeft = token.StartsAtIndex + offset;
            Console.Write(tableRow[token] ? &quot;T&quot; : &quot;F&quot;);
        } Console.WriteLine();
    }
}
</pre>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/antimatroid.wordpress.com/519/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/antimatroid.wordpress.com/519/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/antimatroid.wordpress.com/519/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/antimatroid.wordpress.com/519/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/antimatroid.wordpress.com/519/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/antimatroid.wordpress.com/519/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/antimatroid.wordpress.com/519/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/antimatroid.wordpress.com/519/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/antimatroid.wordpress.com/519/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/antimatroid.wordpress.com/519/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=antimatroid.wordpress.com&blog=4448583&post=519&subd=antimatroid&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://antimatroid.wordpress.com/2009/03/01/generalized-interpreter-framework-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/62c32c6293d483fc7e1d545c4b9a0ac3?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">lewellen</media:title>
		</media:content>

		<media:content url="http://antimatroid.files.wordpress.com/2009/03/interpreter_components.png" medium="image">
			<media:title type="html">interpreter_components</media:title>
		</media:content>

		<media:content url="http://antimatroid.files.wordpress.com/2009/03/interpreter_uml.png" medium="image">
			<media:title type="html">interpreter_uml</media:title>
		</media:content>
	</item>
		<item>
		<title>Ouroboros: reinventing Nibbles</title>
		<link>http://antimatroid.wordpress.com/2009/02/01/ouroboros-reinventing-nibbles/</link>
		<comments>http://antimatroid.wordpress.com/2009/02/01/ouroboros-reinventing-nibbles/#comments</comments>
		<pubDate>Sun, 01 Feb 2009 07:00:43 +0000</pubDate>
		<dc:creator>lewellen</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[.Net 3.5]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Game Programming]]></category>
		<category><![CDATA[Nibbles]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://antimatroid.wordpress.com/?p=442</guid>
		<description><![CDATA[Introduction
I talked about some classic arcade games in a previous post that I had worked on over the years and mentioned that I&#8217;d get around to posting some implementation details of one of them. A few months later here we are and the following is an overview of the implementation details of Ouroboros- my revisioning [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=antimatroid.wordpress.com&blog=4448583&post=442&subd=antimatroid&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h2>Introduction</h2>
<p>I talked about some classic arcade games in a previous post that I had worked on over the years and mentioned that I&#8217;d get around to posting some implementation details of one of them. A few months later here we are and the following is an overview of the implementation details of Ouroboros- my revisioning of the classic arcade game Nibbles that I enjoyed playing and learning about back in my QBasic days.</p>
<p>This write-up will go over the activities associated with the software development process from specification to implementation. Before I get into the details, here&#8217;s a game play of what is that I&#8217;ll be explaining how to make:</p>
<p><span style="text-align:center; display: block;"><a href="http://antimatroid.wordpress.com/2009/02/01/ouroboros-reinventing-nibbles/"><img src="http://img.youtube.com/vi/GSJCGoDmnqI/2.jpg" alt="" /></a></span></p>
<h2>Specification</h2>
<p>The goal of the game is to collect rewards. Each time a reward is collected, the user&#8217;s score is increased. The snake is constantly moving in the direction last requested by the user. The user can direct the snake to move either left, up, right or down. To make the game more challenging, the snake will grow whenever the snake consumes a reward. The game then ends once the snake spans the entire board or the snake collides with itself. When the snake &#8220;hits&#8221; a wall, its position wraps around the board. When either of the terminating conditions is meet the user is asked if he or she wishes to play again.</p>
<h2>Requirements</h2>
<p>The user may control the direction the snake may move by using the keyboard. The following keys are valid: {&larr;, &uarr;, &rarr;, &darr;} and {a, w, d, s} to the directions {left, up, right and down}.</p>
<p>The game is to be displayed to the user as as command line interface (CLI), 2D graphical user interface (2DGUI) using WinForms and a 3D GUI (3DGUI) using  Windows Presentation Foundation. The CLI and 2DGUI shall appear as boards that the snake and reward appear on. The 3DGUI shall appear as a torus that the snake and reward appear on.</p>
<p>The game may not appear to be slower as the length of the snake increases.</p>
<h2>Design</h2>
<h3>The Board</h3>
<p>The board is a simple coordinate system with a fixed side length <img src='http://l.wordpress.com/latex.php?latex=B&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='B' title='B' class='latex' />. Each <img src='http://l.wordpress.com/latex.php?latex=%5Cvec%7Bx%7D+%5Csubset+%7B+%5C%7B+0%2C+1%2C+%5Cldots+B+-+1+%5C%7D+%7D%5E%7B2%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\vec{x} \subset { \{ 0, 1, \ldots B - 1 \} }^{2}' title='\vec{x} \subset { \{ 0, 1, \ldots B - 1 \} }^{2}' class='latex' /> coordinate may be occupied by at most one snake segment. For each view, a mapping <img src='http://l.wordpress.com/latex.php?latex=f+%3A+M+%5Cto+V&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='f : M \to V' title='f : M \to V' class='latex' /> from the model space, <img src='http://l.wordpress.com/latex.php?latex=M&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='M' title='M' class='latex' />, to the view space, <img src='http://l.wordpress.com/latex.php?latex=V&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='V' title='V' class='latex' />, is necessary to achieve the required behavior. </p>
<p><img src="http://antimatroid.files.wordpress.com/2009/02/snake_space1.png?w=480&#038;h=180" alt="snake_space1" title="snake_space1" width="480" height="180" class="aligncenter size-full wp-image-508" /></p>
<p>For the CLI view, let <img src='http://l.wordpress.com/latex.php?latex=f%28%5Cvec%7Bx%7D%29+%3D+%5Cvec%7Bx%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='f(\vec{x}) = \vec{x}' title='f(\vec{x}) = \vec{x}' class='latex' /> since every coordinate maps one-to-one with a cursor position on the console.</p>
<p>The 2DGUI view requires a scaling factor, <img src='http://l.wordpress.com/latex.php?latex=c+%3E+1&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='c &gt; 1' title='c &gt; 1' class='latex' />, otherwise the board would appear to be too small to play- unless for example, upon a cellphone LCD. Let <img src='http://l.wordpress.com/latex.php?latex=f%28%5Cvec%7Bx%7D%29+%3D+c%5Cvec%7Bx%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='f(\vec{x}) = c\vec{x}' title='f(\vec{x}) = c\vec{x}' class='latex' />. </p>
<p>The 3DGUI view requires an initial mapping from a <img src='http://l.wordpress.com/latex.php?latex=%5Cvec%7Bx%7D+%3D+%28x%2Cy%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\vec{x} = (x,y)' title='\vec{x} = (x,y)' class='latex' /> coordinate to a <img src='http://l.wordpress.com/latex.php?latex=%5Cvec%7By%7D+%3D+%28%5Cvartheta%2C+%5Cvarphi%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\vec{y} = (\vartheta, \varphi)' title='\vec{y} = (\vartheta, \varphi)' class='latex' /> system. This is accomplished by <img src='http://l.wordpress.com/latex.php?latex=g%28%5Cvec%7Bx%7D%29+%3D+%5Cfrac%7B2%5Cpi%7D%7BB%7D%5Cvec%7Bx%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='g(\vec{x}) = \frac{2\pi}{B}\vec{x}' title='g(\vec{x}) = \frac{2\pi}{B}\vec{x}' class='latex' /> where <img src='http://l.wordpress.com/latex.php?latex=B&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='B' title='B' class='latex' /> is the length of the edge of the board. A torus is defined in terms of an interior radius, <img src='http://l.wordpress.com/latex.php?latex=R&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='R' title='R' class='latex' />, and the swept radius, <img src='http://l.wordpress.com/latex.php?latex=r&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='r' title='r' class='latex' />. Thus a torus is defined as the following: </p>
<p><img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle+%28f+%5Ccirc+g%29%28%5Cvec%7Bx%7D%29+%3D+%5Cbegin%7Bpmatrix%7D%28R+%2B+r+cos%28%5Cvarphi%29%29cos%28%5Cvartheta%29%5C%5C%28R+%2B+r+cos%28%5Cvarphi%29%29cos%28%5Cvartheta%29%5C%5Cr+sin%28%5Cvarphi%29%5Cend%7Bpmatrix%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\displaystyle (f \circ g)(\vec{x}) = \begin{pmatrix}(R + r cos(\varphi))cos(\vartheta)\\(R + r cos(\varphi))cos(\vartheta)\\r sin(\varphi)\end{pmatrix}' title='\displaystyle (f \circ g)(\vec{x}) = \begin{pmatrix}(R + r cos(\varphi))cos(\vartheta)\\(R + r cos(\varphi))cos(\vartheta)\\r sin(\varphi)\end{pmatrix}' class='latex' /> </p>
<h3>The Snake</h3>
<p>The snake is conceptually a sequence of segments that I choose to represent as a singly-linked list where each node contains a pointer to the next segment and the segment&#8217;s position. The following illustrates a snake of length five:</p>
<p><img src="http://antimatroid.files.wordpress.com/2009/01/snake_model.png?w=480&#038;h=360" alt="snake_model" title="snake_model" width="480" height="360" class="aligncenter size-full wp-image-444" /></p>
<p>To achieve movement, the position of the head segment is passed to the next segment, and the next segment on to its next segment so on and so forth until the tail is reached.</p>
<p>Each time the snake moves, its <img src='http://l.wordpress.com/latex.php?latex=x%5E%7B%28k%29%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='x^{(k)}' title='x^{(k)}' class='latex' /> coordinate will be calculated as <img src='http://l.wordpress.com/latex.php?latex=x_%7Bn%2B1%7D%5E%7B%28k%29%7D+%3D+x_%7Bn%7D%5E%7B%28k%29%7D+%2B+dx_%7B%5Ctext%7Bdir%7D%7D%5E%7B%28k%29%7D+%5Cpmod%7BB%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='x_{n+1}^{(k)} = x_{n}^{(k)} + dx_{\text{dir}}^{(k)} \pmod{B}' title='x_{n+1}^{(k)} = x_{n}^{(k)} + dx_{\text{dir}}^{(k)} \pmod{B}' class='latex' />.</p>
<p>Scoring should be done in such a way that rewards become more valuable as time continues. Since the initial length of the snake is 1, a snake of length <img src='http://l.wordpress.com/latex.php?latex=N&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='N' title='N' class='latex' /> will have collected <img src='http://l.wordpress.com/latex.php?latex=N+-+1&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='N - 1' title='N - 1' class='latex' /> rewards. Thus, let <img src='http://l.wordpress.com/latex.php?latex=S%28N%29+%3D+%5Csum_%7Bn+%3D+0%7D%5E%7BN%7D%7B100+%281+-+e%5E%7B%5Cfrac%7B-%28N+-+1%29%7D%7B10%7D%7D%29%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='S(N) = \sum_{n = 0}^{N}{100 (1 - e^{\frac{-(N - 1)}{10}})}' title='S(N) = \sum_{n = 0}^{N}{100 (1 - e^{\frac{-(N - 1)}{10}})}' class='latex' /> represent the scoring function. Where 100 is maximum score for a reward, -1/10 is the decay factor.</p>
<p>Once a snake has consumed a reward, a new node is added to the tail with a location identical to the tail location.</p>
<p>To determine if a the snake is on top of a reward, each segment&#8217;s position will be compared to the reward&#8217;s position. If a segment and reward are identical then the snake is on top of the reward. If no match is found, then the snake is not on top of the reward. This process can be done in linear time. Constant time, if you choose to generate rewards that are not on top of snake.</p>
<p>When drawing the game it is useful to observe that the only thing that ever changes between time step is the the head and tail of the snake. Thus, it is prudent to only draw the current head position and erase the previous tail position. This will produce a length independent drawing method so that the game does not appear to be slower as the snake gets larger.</p>
<p>Implementations may be written using recursion, but beware that with larger board sizes that you run the risk of a stack overflow on systems that don&#8217;t give you much memory to work with. Using a cursor to search the singly-linked list may be more appropriate when using larger board sizes.</p>
<h2>Implementation</h2>
<p>I decided to go with a Model-View-Controller (MVC) pattern since I&#8217;d like to be able to view the CLI, 2DGUI and 3DGUI all at once. Below is a complete UML class diagram of all the MVC components that I choose to implement. </p>
<p><a href="http://antimatroid.files.wordpress.com/2009/02/snake21.png"><img src="http://antimatroid.files.wordpress.com/2009/02/snake21.png?w=700&#038;h=548" alt="snake21" title="snake21" width="700" height="548" class="aligncenter size-full wp-image-483" /></a></p>
<p>The following is the core engine of the game; it perform each of the core tasks of performing logic, drawing the board, getting user input and maintaining time.</p>
<pre class="brush: csharp;">
public class Program {
    [STAThread]
    static public void Main(string[] args) {
        List views = new List(new IGameView[] {
            new CLIGameView(),
            new GUI2DGameView(),
            new GUI3DGameView()
        });
        IGameController controller = new CLIGameController();

        int boardSize = 32;
        double maxScore = double.MinValue;

        views.ForEach((view) =&gt; view.initialize(boardSize));

        do {
            SnakeDirection desiredDirection = SnakeDirection.Up;
            SnakePoint reward = SnakePoint.Random(boardSize);
            SnakeSegment snake = new SnakeSegment(SnakePoint.Random(boardSize));

            views.ForEach((view) =&gt; view.drawBoard());

            do {
                if (controller.InputAvailable) {
                    SnakeDirection possible = controller.getDirection();
                    if (possible != SnakeDirection.Nop)
                        desiredDirection = possible;
                }

                if (snake.isOnTopOf(reward)) {
                    snake.grow();

                    if (snake.Length != boardSize * boardSize) {
                        do {
                            reward = SnakePoint.Random(boardSize);
                        } while (snake.isOnTopOf(reward));
                    }

                    maxScore = Math.Max(maxScore, snake.Score);

                    views.ForEach((view) =&gt; view.drawScore(snake.Score, maxScore));
                }

                SnakePoint oldTail = snake.Tail.Location;

                snake.move(desiredDirection, boardSize);

                views.ForEach((view) =&gt; view.drawSnake(snake, oldTail));
                views.ForEach((view) =&gt; view.drawReward(reward));

                System.Threading.Thread.Sleep(1000 / 15);
            } while (!snake.selfCollision());

            views.ForEach((view) =&gt; view.drawGameOver());
            views.ForEach((view) =&gt; view.drawPlayAgain());

        } while (controller.playAgain());

        views.ForEach((view) =&gt; view.deinitialize());
        views.Clear();
    }
}
</pre>
<pre class="brush: csharp;">
public class GUI3DGameView : IGameView {
    private int boardSize;
    private Form canvas;
    private ScoreLabel score;
    private TorusScene scene;

    public int BoardSize {
        get { return boardSize; }
    }

    public GUI3DGameView() {
        canvas = new Form();
        canvas.BackColor = System.Drawing.Color.FromArgb(0x33,0x33,0x33);
        canvas.FormBorderStyle = FormBorderStyle.FixedToolWindow;
        canvas.MaximizeBox = false;
        canvas.MinimizeBox = false;
        canvas.SizeGripStyle = SizeGripStyle.Hide;
        canvas.Text = &quot;GUI3DGameView&quot;;
        canvas.ClientSize = new Size(384, 384);

        ElementHost host = new ElementHost();
        host.Child = scene = new TorusScene();
        host.Dock = DockStyle.Fill;
        canvas.Controls.Add(host);

        score = new ScoreLabel();
        score.Dock = DockStyle.Bottom;

        canvas.Controls.Add(score);
    }

    public void initialize(int boardSize) {
        this.boardSize = boardSize;

        if (!canvas.Visible)
            canvas.Show();
    }

    public void deinitialize() {
        canvas.Dispose();
    }

    public void drawBoard() {
        score.reset();
        scene.removeSnake();
    }

    public void drawGameOver() {

    }

    public void drawPlayAgain() {

    }

    public void drawReward(SnakePoint reward) {
        scene.moveReward(reward.x, reward.y);
    }

    public void drawScore(double current, double max) {
        score.setScore(current, max);
    }

    public void drawSnake(SnakeSegment head, SnakePoint oldTail) {
        scene.addSegment(head.Location.x, head.Location.y, head.Length);
    }
}
</pre>
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Media3D;

namespace Snake.View.GUI3D {
    public class TorusScene : Viewport3D {
        private Queue&lt;ModelVisual3D&gt; patches;
        private ModelVisual3D reward;

        public TorusScene() {
            Camera = new PerspectiveCamera(new Point3D(10, 10, 10), new Vector3D(-10, -10, -10), new Vector3D(0, 1, 0), 60);

            AmbientLight aLight = new AmbientLight(Color.FromRgb(0x33,0x33,0x33));
            ModelVisual3D aLightHost = new ModelVisual3D();
            aLightHost.Content = aLight;
            Children.Add(aLightHost);

            DirectionalLight light = new DirectionalLight(Colors.Orange, new Vector3D(0, -10, 0));
            ModelVisual3D lightHost = new ModelVisual3D();
            lightHost.Content = light;
            Children.Add(lightHost);

            DirectionalLight rearLight = new DirectionalLight(Colors.LightBlue, new Vector3D(0, 10, 0));
            ModelVisual3D rearLightHost = new ModelVisual3D();
            rearLightHost.Content = rearLight;
            Children.Add(rearLightHost);

            Model3DGroup torus = new Model3DGroup();
            double N = 16.0;
            double dTheta = Math.PI / N, dPhi = Math.PI / N;
            double R = 5.0, r = 2.0;

            Color surface = SnakeColors.MGround;

            for (double theta = 0.0; theta &lt;= 2.0 * Math.PI; theta += dTheta) {
                for (double phi = 0.0; phi &lt;= 2.0 * Math.PI; phi += dPhi) {
                    Point3D[] S = square(dTheta, dPhi, R, r, theta, phi);
                    torus.Children.Add(triangle(S[0], S[1], S[3], surface));
                    torus.Children.Add(triangle(S[3], S[2], S[0], surface));
                }
            }

            ModelVisual3D model = new ModelVisual3D();
            model.Content = torus;
            Children.Add(model);

            patches = new Queue&lt;ModelVisual3D&gt;();
        }

        public void addSegment(double u, double v, int max) {
            ModelVisual3D snake = addSphere(u, v, 0.5, SnakeColors.MHead);

            if (patches.Count != 0 &amp;&amp; patches.Count == max)
                Children.Remove(patches.Dequeue());
            patches.Enqueue(snake);

            Point3D[] S = square(Math.PI / 16.0, Math.PI / 16.0, 5.0, 2.5, u / 16.0 * Math.PI, v / 16.0 * Math.PI);
            double r = 30.0 / Math.Sqrt(3.0) / Math.Sqrt(S[0].X * S[0].X + S[0].Y * S[0].Y + S[0].Z * S[0].Z);
            Camera.SetValue(PerspectiveCamera.PositionProperty, new Point3D(r * S[0].X, r * S[0].Y, r * S[0].Z));
            Camera.SetValue(PerspectiveCamera.LookDirectionProperty, new Vector3D(-r * S[0].X, -r * S[0].Y, -r * S[0].Z));
        }

        public void moveReward(double u, double v) {
            if (reward != null) {
                Children.Remove(reward);
                reward = null;
            }

            reward = addSphere(u, v, 0.25, SnakeColors.MReward);
        }

        public void removeSnake() {
            while (patches.Count != 0)
                Children.Remove(patches.Dequeue());
        }

        private ModelVisual3D addSphere(double u, double v, double r, Color color) {
            Model3DGroup sphere = new Model3DGroup();
            Point3D center = parameterized(5.0, 2.0 + r, u / 16.0 * Math.PI, v / 16.0 * Math.PI);
            Vector3D vec = new Vector3D(center.X, center.Y, center.Z);

            double dTheta, dPhi;
            dTheta = dPhi = Math.PI / 3.0;

            for (double theta = 0.0; theta &lt;= 2.0 * Math.PI; theta += dTheta) {
                for (double phi = 0.0; phi &lt;= 2.0 * Math.PI; phi += dPhi) {
                    Point3D[] S = square(dTheta, dPhi, 0, r, theta, phi);
                    for (int n = 0; n &lt; S.Length; n++)
                        S[n] = Point3D.Add(S[n], vec);

                    sphere.Children.Add(triangle(S[0], S[1], S[3], color));
                    sphere.Children.Add(triangle(S[3], S[2], S[0], color));
                }
            }

            ModelVisual3D model = new ModelVisual3D();
            model.Content = sphere;
            Children.Add(model);

            return model;
        }

        private Point3D parameterized(double R, double r, double theta, double phi) {
            return new Point3D(
                (R + r * Math.Cos(phi)) * Math.Cos(theta),
                r * Math.Sin(phi),
                (R + r * Math.Cos(phi)) * Math.Sin(theta)
            );
        }

        private Point3D[] square(double dTheta, double dPhi, double R, double r, double theta, double phi) {
            return new Point3D[] {
                parameterized(R, r, theta, phi),
                parameterized(R, r, theta, phi + dPhi),
                parameterized(R, r, theta + dTheta, phi),
                parameterized(R, r, theta + dTheta, phi + dPhi)
            };
        }

        private Model3DGroup triangle(Point3D a, Point3D b, Point3D c, Color color) {
            MeshGeometry3D mesh = new MeshGeometry3D();
            mesh.Positions.Add(a);
            mesh.Positions.Add(b);
            mesh.Positions.Add(c);
            mesh.TriangleIndices.Add(0);
            mesh.TriangleIndices.Add(1);
            mesh.TriangleIndices.Add(2);

            Material material = new DiffuseMaterial(new SolidColorBrush(color));
            GeometryModel3D model = new GeometryModel3D(mesh, material);
            Model3DGroup group = new Model3DGroup();
            group.Children.Add(model);
            return group;
        }
    }
}
</pre>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/antimatroid.wordpress.com/442/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/antimatroid.wordpress.com/442/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/antimatroid.wordpress.com/442/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/antimatroid.wordpress.com/442/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/antimatroid.wordpress.com/442/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/antimatroid.wordpress.com/442/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/antimatroid.wordpress.com/442/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/antimatroid.wordpress.com/442/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/antimatroid.wordpress.com/442/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/antimatroid.wordpress.com/442/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=antimatroid.wordpress.com&blog=4448583&post=442&subd=antimatroid&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://antimatroid.wordpress.com/2009/02/01/ouroboros-reinventing-nibbles/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/62c32c6293d483fc7e1d545c4b9a0ac3?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">lewellen</media:title>
		</media:content>

		<media:content url="http://img.youtube.com/vi/GSJCGoDmnqI/2.jpg" medium="image" />

		<media:content url="http://antimatroid.files.wordpress.com/2009/02/snake_space1.png" medium="image">
			<media:title type="html">snake_space1</media:title>
		</media:content>

		<media:content url="http://antimatroid.files.wordpress.com/2009/01/snake_model.png" medium="image">
			<media:title type="html">snake_model</media:title>
		</media:content>

		<media:content url="http://antimatroid.files.wordpress.com/2009/02/snake21.png" medium="image">
			<media:title type="html">snake21</media:title>
		</media:content>
	</item>
		<item>
		<title>Embedded Streaming Radio Project</title>
		<link>http://antimatroid.wordpress.com/2009/01/01/embedded-streaming-radio-project/</link>
		<comments>http://antimatroid.wordpress.com/2009/01/01/embedded-streaming-radio-project/#comments</comments>
		<pubDate>Thu, 01 Jan 2009 19:52:16 +0000</pubDate>
		<dc:creator>lewellen</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Internet Radio]]></category>
		<category><![CDATA[Project]]></category>

		<guid isPermaLink="false">http://antimatroid.wordpress.com/?p=415</guid>
		<description><![CDATA[It&#8217;s been a while since I posted anything here, partly a function of a lack of interest, time and viewership. Part of my new years resolution was to try and post something around here maybe once a month. So, I figure I&#8217;d post on a hardware project that I&#8217;ve been tinkering around with the past [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=antimatroid.wordpress.com&blog=4448583&post=415&subd=antimatroid&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><i>It&#8217;s been a while since I posted anything here, partly a function of a lack of interest, time and viewership. Part of my new years resolution was to try and post something around here maybe once a month. So, I figure I&#8217;d post on a hardware project that I&#8217;ve been tinkering around with the past couple months. It took me a while to gather this info so hopefully it will save others time looking to build a similar project.</i></p>
<p>I enjoy listening to the <a href="http://www.shoutcast.com/">SHOUTcast</a> streaming radio service using <a href="http://www.winamp.com/">Winamp</a> but after awhile I really want to be able to just listen to the stations on my shelf stereo system rather than on my laptop. Thus a pretty simple little idea:</p>
<blockquote><p>Build a device that has a SHOUTcast complaint client that I can configure to point to a local shoutcast sever running on my laptop so that I can stream my mp3 collection or listen to any streaming station through my stereo shelf system.</p></blockquote>
<p>Given that simple problem statement, I started thinking about how I would go about getting everything set up:</p>
<p><img src="http://antimatroid.files.wordpress.com/2009/01/stereo_network.png?w=584&#038;h=303" alt="stereo_network" title="stereo_network" width="584" height="303" class="aligncenter size-full wp-image-585" /></p>
<p>With all of that in mind, I have enough for an initial laundry list of requirements for the hardware component:</p>
<ul>
<li>RCA out to connect to my stereo system</li>
<li>Built-in 1000/100/10 Gigabit Ethernet or 802.11b/g wireless to access the radio streams</li>
<li>http server running on port 80/8080 so that I could remotely configure it all</li>
<li>Maybe include a LCD for kicks or a touch screen for album art/misc content</li>
</ul>
<p>Now there are couple paths to go down from here: the first was to run with the project thinking that I could go out and purchase all the hardware components described above- assemble them, write a simple http server and do some low level assembly. Second option is to go out and see what available open source options are out there and try to purchase a pre-built embedded system. The last option was to search the market for a similar product.</p>
<p>The first option sounds like a lot of fun, but doesn&#8217;t seem very feasible from a time stand point. Third option does offer a perfect solution through Logitech&#8217;s <a href="http://www.slimdevices.com/pi_squeezebox.html">Squeezebox Classic</a> which is great from a time stand point but not so great from a satisfaction standpoint so that leads one to option number two.</p>
<p>So the hunt was on to find the perfect combo of pre-existing components and figuring out how to get them all to play nicely. First thing I went looking for was to see if there were any open source SHOUTcast clients out there. Turns out there is a really great project out there called the <a href="http://snackamp.sourceforge.net/">SnackAmp Music Player</a> that does everything that I&#8217;d like to do. In fact, it comes along with a great remote control feature targeted exactly at the kind of scenario I&#8217;m trying to build. </p>
<p>Next step was to look at what platforms SnackAmp would run on. Being an open source project they have builds available for standard i386 Linux distributions and of course Microsoft Windows. Not being a person particular about operating systems I decided that I would go with Linux since it&#8217;s free and since there are a number of minimalistic distributions out there.</p>
<p>Finally, I needed to decide on a piece of hardware that would meet my needs. I want something compact that I can place next to my stereo that is low power and quiet- something a little smaller than a DSL modem or smaller than standard CD wallet. Looking around it seems that <a href="http://www.via.com.tw/en/index.jsp">VIA</a> is the key player in the mini-itx market which the form factor of most of the boards I was looking at. <a href="http://www.mini-itx.com/">mini-itx.com</a> and <a href="http://www.mini-box.com/site/index.html">mini-box.com</a> have a number of solutions but few of their offerings had the 802.11b/g that I was looking for. I&#8217;m not 100% decided on what I would like to purchase from either site, but the average cost appears to be around 250-300 USD for a board, memory and enclosure.</p>
<p>Surmising all the above, I think I&#8217;d like to go with the following technology stack:</p>
<table border="1" width="95%" cellpadding="0" cellspacing="0">
<tr>
<td valign="bottom" align="center" rowspan="3">Stereo System</td>
<td align="center">SnackAmp</td>
<td align="center">Firefox</td>
<td align="center">SHOUTcast Server</td>
<td valign="bottom" align="center" rowspan="3">NAS</td>
</tr>
<tr>
<td align="center"><a href="http://minimalinux.org/ttylinux/">ttylinux</a></td>
<td align="center" colspan="2">Windows XP SP2</td>
</tr>
<tr>
<td align="center">mini itx</td>
<td align="center" colspan="2">Laptop</td>
</tr>
<tr>
<td />
<td align="center" colspan="4">802.11b/g LAN</td>
</tr>
</table>
<p>Total cost would be in the 250-300 USD range -add on an additional 100-300 USD for a cheap NAS- since the hardware is the only thing that I need to get. Now, I mentioned previously that Logitech offers an almost identical device for 300 USD (at the time of this post). So the question arises, which one is the better buy? </p>
<p>The commercial solution has been tested and it works with multiple services and seems to have a pretty large community built around it- but then again there&#8217;s nothing to learn other than how to use it. On the other hand, a custom built solution can be repurposed to fit future use cases that I have yet to think up so it may offer in the long run a great utility compared to its competition.</p>
<p>Short answer is that I have yet to decide on which option is right since I&#8217;m still looking around to see what&#8217;s out there. (If you know of additional products post them in the comments). If I move forward with any of this I&#8217;ll be sure to post details as they come along.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/antimatroid.wordpress.com/415/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/antimatroid.wordpress.com/415/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/antimatroid.wordpress.com/415/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/antimatroid.wordpress.com/415/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/antimatroid.wordpress.com/415/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/antimatroid.wordpress.com/415/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/antimatroid.wordpress.com/415/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/antimatroid.wordpress.com/415/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/antimatroid.wordpress.com/415/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/antimatroid.wordpress.com/415/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=antimatroid.wordpress.com&blog=4448583&post=415&subd=antimatroid&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://antimatroid.wordpress.com/2009/01/01/embedded-streaming-radio-project/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/62c32c6293d483fc7e1d545c4b9a0ac3?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">lewellen</media:title>
		</media:content>

		<media:content url="http://antimatroid.files.wordpress.com/2009/01/stereo_network.png" medium="image">
			<media:title type="html">stereo_network</media:title>
		</media:content>
	</item>
		<item>
		<title>Radial tree drawing</title>
		<link>http://antimatroid.wordpress.com/2008/08/31/radial-tree-drawing/</link>
		<comments>http://antimatroid.wordpress.com/2008/08/31/radial-tree-drawing/#comments</comments>
		<pubDate>Mon, 01 Sep 2008 01:05:39 +0000</pubDate>
		<dc:creator>lewellen</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Graph Theory]]></category>
		<category><![CDATA[Tree Drawing]]></category>

		<guid isPermaLink="false">http://antimatroid.wordpress.com/?p=333</guid>
		<description><![CDATA[
Although not as interesting as a sunburst diagram, the radial tree view can hold its color against a number of more primitive information visualizations. A radial tree view places the root at the center of the screen then fans out each child node. Each child node then fans out its children within a restricted span [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=antimatroid.wordpress.com&blog=4448583&post=333&subd=antimatroid&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>
Although not as interesting as a sunburst diagram, the radial tree view can hold its color against a number of more primitive information visualizations. A radial tree view places the root at the center of the screen then fans out each child node. Each child node then fans out its children within a restricted span and continues on until each leaf is reached. The strengths of the technique allow for any easy to digest depiction of the structure behind the data in a compact space. A common application is visualizing computer networks. It is worthwhile to examine the algorithm behind the technique because it is an exercise in identifying simplicity.
</p>
<p>
While in college, I would have approached this problem by trying to identify the location of nodes in terms of <img src='http://l.wordpress.com/latex.php?latex=%28r%2C+%5Ctheta%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='(r, \theta)' title='(r, \theta)' class='latex' /> after all, I want a radial tree view- makes sense to sprint out the gate with a polar system right? While possible, this is a bad path to head down, as you end up drowning in a sea of extraneous details. Rather, it is better to think in terms of <img src='http://l.wordpress.com/latex.php?latex=%28x%2Cy%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='(x,y)' title='(x,y)' class='latex' /> and then map to <img src='http://l.wordpress.com/latex.php?latex=%28r%2C+%5Ctheta%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='(r, \theta)' title='(r, \theta)' class='latex' />. To clarify that position, let&#8217;s think about how we&#8217;d go about drawing the run of the mill tree view as in the figure below:
</p>
<p><img src="http://antimatroid.files.wordpress.com/2008/08/radialtree_normal.png?w=700&#038;h=233" alt="radialtree_normal" title="radialtree_normal" width="700" height="233" class="aligncenter size-full wp-image-599" /></p>
<p>
First some observations:</p>
<ul>
<li>Every node at a given depth lies on the same line.</li>
<li>Every child at a given depth is given an equal share of horizontal space independent of necessity relative to the space owned by its parent.</li>
</ul>
<p>We can construct a simple recursive definition for drawing the tree if we think about these two facts. Given a node, we want to center the node at the top of a region then carve up a region into the number of child nodes where each sub region is equally wide and the same height as the parent minus a layering distance, then draw a line from the parent node to the child node. Continue doing so until all of the nodes have been drawn. All that remains is mapping this tree to the radial tree view below:
</p>
<p><img src="http://antimatroid.files.wordpress.com/2008/08/radialtree1.png?w=480&#038;h=480" alt="radialtree1" title="radialtree1" width="480" height="480" class="aligncenter size-full wp-image-598" /></p>
<p>
To achieve this last step, we want to map each node at <img src='http://l.wordpress.com/latex.php?latex=%28x%2Cy%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='(x,y)' title='(x,y)' class='latex' /> to a point <img src='http://l.wordpress.com/latex.php?latex=%5Chat%7BC%7D+%2B+r+%5Ccdot%28cos%28%5Ctheta%29%2C+sin%28%5Ctheta%29%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\hat{C} + r \cdot(cos(\theta), sin(\theta))' title='\hat{C} + r \cdot(cos(\theta), sin(\theta))' class='latex' /> Where <img src='http://l.wordpress.com/latex.php?latex=%5Chat%7BC%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\hat{C}' title='\hat{C}' class='latex' /> is the center of the display area. The radius is simply the node&#8217;s present <img src='http://l.wordpress.com/latex.php?latex=y&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='y' title='y' class='latex' /> coordinate. <img src='http://l.wordpress.com/latex.php?latex=%5Ctheta&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\theta' title='\theta' class='latex' /> can be determined as the ratio between the node&#8217;s present <img src='http://l.wordpress.com/latex.php?latex=x&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='x' title='x' class='latex' /> coordinate and the display width times <img src='http://l.wordpress.com/latex.php?latex=2+%5Cpi&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='2 \pi' title='2 \pi' class='latex' />. And thus, the mapping is complete.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/antimatroid.wordpress.com/333/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/antimatroid.wordpress.com/333/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/antimatroid.wordpress.com/333/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/antimatroid.wordpress.com/333/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/antimatroid.wordpress.com/333/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/antimatroid.wordpress.com/333/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/antimatroid.wordpress.com/333/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/antimatroid.wordpress.com/333/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/antimatroid.wordpress.com/333/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/antimatroid.wordpress.com/333/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/antimatroid.wordpress.com/333/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/antimatroid.wordpress.com/333/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=antimatroid.wordpress.com&blog=4448583&post=333&subd=antimatroid&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://antimatroid.wordpress.com/2008/08/31/radial-tree-drawing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/62c32c6293d483fc7e1d545c4b9a0ac3?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">lewellen</media:title>
		</media:content>

		<media:content url="http://antimatroid.files.wordpress.com/2008/08/radialtree_normal.png" medium="image">
			<media:title type="html">radialtree_normal</media:title>
		</media:content>

		<media:content url="http://antimatroid.files.wordpress.com/2008/08/radialtree1.png" medium="image">
			<media:title type="html">radialtree1</media:title>
		</media:content>
	</item>
		<item>
		<title>Solutions to some Microsoft interview questions</title>
		<link>http://antimatroid.wordpress.com/2008/08/24/microsoft-interview-questions/</link>
		<comments>http://antimatroid.wordpress.com/2008/08/24/microsoft-interview-questions/#comments</comments>
		<pubDate>Mon, 25 Aug 2008 01:00:01 +0000</pubDate>
		<dc:creator>lewellen</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Brain Teaser]]></category>
		<category><![CDATA[Interview Questions]]></category>
		<category><![CDATA[Microsoft]]></category>

		<guid isPermaLink="false">http://antimatroid.wordpress.com/?p=68</guid>
		<description><![CDATA[
A couple of weeks ago, someone on reddit posted a link to a collection of Microsoft Interview Questions. As someone who interviewed with them while in college, I was curious to see what kind question they were asking folks. After reviewing the list, I thought I&#8217;d work out a few that looked interesting:


Imagine an analog [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=antimatroid.wordpress.com&blog=4448583&post=68&subd=antimatroid&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>
A couple of weeks ago, someone on <a href="http://www.reddit.com/">reddit</a> posted a link to a collection of <a href="http://www.sellsbrothers.com/fun/msiview/default.aspx?content=question.htm">Microsoft Interview Questions</a>. As someone who interviewed with them while in college, I was curious to see what kind question they were asking folks. After reviewing the list, I thought I&#8217;d work out a few that looked interesting:
</p>
<blockquote><p>
Imagine an analog clock set to 12 o&#8217;clock. Note that the hour and minute hands overlap. How many times each day do both the hour and minute hands overlap? How would you determine the exact times of the day that this occurs?
</p></blockquote>
<p><img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle+%5Ctext%7BLet+%7D+%5Ctheta_%7Bh%7D%28t%29+%3D+%5Cfrac%7B2%5Cpi%7D%7B43200%7Dt+%2C+%5Ctheta_%7Bm%7D%28t%29+%3D+%5Cfrac%7B2%5Cpi%7D%7B3600%7D+t+%5Cin+%5Cmathbb%7BR%7D+%5Cto+%5Cmathbb%7BR%7D%2C+t+%5Cin+%5B0%2C+86400%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\displaystyle \text{Let } \theta_{h}(t) = \frac{2\pi}{43200}t , \theta_{m}(t) = \frac{2\pi}{3600} t \in \mathbb{R} \to \mathbb{R}, t \in [0, 86400)' title='\displaystyle \text{Let } \theta_{h}(t) = \frac{2\pi}{43200}t , \theta_{m}(t) = \frac{2\pi}{3600} t \in \mathbb{R} \to \mathbb{R}, t \in [0, 86400)' class='latex' /></p>
<p><img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle+%5Clvert+%5Ctheta_%7Bh%7D%28t%29+-+%5Ctheta_%7Bm%7D%28t%29+%5Crvert+%5Cequiv+0+%5Cpmod%7B2%5Cpi%7D+%5CRightarrow+%5Cfrac%7B39600%7D%7B155520000%7D+2%5Cpi+t++%5Cequiv+0+%5Cpmod%7B2%5Cpi%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\displaystyle \lvert \theta_{h}(t) - \theta_{m}(t) \rvert \equiv 0 \pmod{2\pi} \Rightarrow \frac{39600}{155520000} 2\pi t  \equiv 0 \pmod{2\pi}' title='\displaystyle \lvert \theta_{h}(t) - \theta_{m}(t) \rvert \equiv 0 \pmod{2\pi} \Rightarrow \frac{39600}{155520000} 2\pi t  \equiv 0 \pmod{2\pi}' class='latex' /></p>
<p><img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle+%5CRightarrow+t_%7Bk%7D+%3D+%5Cfrac%7B43200%7D%7B11%7D+k%2C+k+%5Cin+%5B0%2C+22%29&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\displaystyle \Rightarrow t_{k} = \frac{43200}{11} k, k \in [0, 22)' title='\displaystyle \Rightarrow t_{k} = \frac{43200}{11} k, k \in [0, 22)' class='latex' /></p>
<p>Thus<sup>*</sup>: 12:00:00 AM, 01:05:27 AM, 02:10:54 AM, 03:16:21 AM, 04:21:49 AM, 05:27:16 AM, 06:32:43 AM, 07:38:10 AM, 08:43:38 AM, 09:49:05 AM, 10:54:32 AM, 12:00:00 PM, 01:05:27 PM, 02:10:54 PM, 03:16:21 PM, 04:21:49 PM, 05:27:16 PM, 06:32:43 PM, 07:38:10 PM, 08:43:38 PM, 09:49:05 PM and 10:54:32 PM.</p>
<p><sup>*</sup> Floor the conversion from <img src='http://l.wordpress.com/latex.php?latex=t&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='t' title='t' class='latex' /> to hour, minute and second of day.</p>
<blockquote><p>
Pairs of primes separated by a single number are called prime pairs. Examples are 17 and 19. Prove that the number between a prime pair is always divisible by 6 (assuming both numbers in the pair are greater than 6). Now prove that there are no &#8216;prime triples.&#8217;
</p></blockquote>
<p>Assuming:<br />
<img src='http://l.wordpress.com/latex.php?latex=%5Ctext%7BLet+%7D+n%2C+r+%5Cin+%5Cmathbb%7BN%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\text{Let } n, r \in \mathbb{N}' title='\text{Let } n, r \in \mathbb{N}' class='latex' /><br />
<img src='http://l.wordpress.com/latex.php?latex=p+%3D+6n+%5Cpm+r+%2C+r+%5Cin+%5C%7B+0%2C+2+%5C%7D+%5CRightarrow+3%7Cp&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='p = 6n \pm r , r \in \{ 0, 2 \} \Rightarrow 3|p' title='p = 6n \pm r , r \in \{ 0, 2 \} \Rightarrow 3|p' class='latex' /><br />
<img src='http://l.wordpress.com/latex.php?latex=p+%3D+6n+%5Cpm+r+%2C+r+%5Cin+%5C%7B+3%2C+4+%5C%7D+%5CRightarrow+2%7Cp&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='p = 6n \pm r , r \in \{ 3, 4 \} \Rightarrow 2|p' title='p = 6n \pm r , r \in \{ 3, 4 \} \Rightarrow 2|p' class='latex' /><br />
<img src='http://l.wordpress.com/latex.php?latex=p+%3D+6n+%5Cpm+r+%2C+r+%5Cin+%5C%7B1%2C+5+%5C%7D+%5CRightarrow+1%7Cp+%5Cwedge+p%7Cp&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='p = 6n \pm r , r \in \{1, 5 \} \Rightarrow 1|p \wedge p|p' title='p = 6n \pm r , r \in \{1, 5 \} \Rightarrow 1|p \wedge p|p' class='latex' /><br />
<img src='http://l.wordpress.com/latex.php?latex=%5Ctherefore+%28%5Cforall+p+%3E+3%29+%5Cin+%5Cmathbb%7BP%7D%2C+p+%3D+6n+%5Cpm+r%2C+r+%5Cin+%5C%7B1%2C+5%5C%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\therefore (\forall p &gt; 3) \in \mathbb{P}, p = 6n \pm r, r \in \{1, 5\}' title='\therefore (\forall p &gt; 3) \in \mathbb{P}, p = 6n \pm r, r \in \{1, 5\}' class='latex' /></p>
<p>Twin Primes:<br />
<img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle+%5Ctext%7BLet+%7D+p+%3D+6n+-+1%2C+q+%3D+6n+%2B+1+%5Cin+%5Cmathbb%7BP%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\displaystyle \text{Let } p = 6n - 1, q = 6n + 1 \in \mathbb{P}' title='\displaystyle \text{Let } p = 6n - 1, q = 6n + 1 \in \mathbb{P}' class='latex' /><br />
<img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle+n%2C+r+%3D+%5Cfrac%7Bp%2Bq%7D%7B2%7D+%5Cin+%5Cmathbb%7BN%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\displaystyle n, r = \frac{p+q}{2} \in \mathbb{N}' title='\displaystyle n, r = \frac{p+q}{2} \in \mathbb{N}' class='latex' /><br />
<img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle%5CRightarrow+r+%3D+%5Cfrac%7B6n+-+1+%2B+6n+%2B+1%7D%7B2%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\displaystyle\Rightarrow r = \frac{6n - 1 + 6n + 1}{2}' title='\displaystyle\Rightarrow r = \frac{6n - 1 + 6n + 1}{2}' class='latex' /><br />
<img src='http://l.wordpress.com/latex.php?latex=%5CRightarrow+r+%3D+6n&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\Rightarrow r = 6n' title='\Rightarrow r = 6n' class='latex' /><br />
<img src='http://l.wordpress.com/latex.php?latex=%5Ctherefore+6%7Cr&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\therefore 6|r' title='\therefore 6|r' class='latex' /></p>
<p>Prime Triples:<br />
<img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle+%5Ctext%7BLet+%7D+u+%3D+6n+-+1%2C+v+%3D+6n+%2B+1%2C+v+%3D+6m+-+1%2C+w+%3D+6m+%2B+1+%5Cin+%5Cmathbb%7BP%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\displaystyle \text{Let } u = 6n - 1, v = 6n + 1, v = 6m - 1, w = 6m + 1 \in \mathbb{P}' title='\displaystyle \text{Let } u = 6n - 1, v = 6n + 1, v = 6m - 1, w = 6m + 1 \in \mathbb{P}' class='latex' /><br />
<img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle+n+%3C+m+%5Cin+%5Cmathbb%7BN%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\displaystyle n &lt; m \in \mathbb{N}' title='\displaystyle n &lt; m \in \mathbb{N}' class='latex' /><br />
<img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle+6n+%2B+1+%3D+6m+-+1+%5CRightarrow+m+-+n+%3D+%5Cfrac%7B1%7D%7B3%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\displaystyle 6n + 1 = 6m - 1 \Rightarrow m - n = \frac{1}{3}' title='\displaystyle 6n + 1 = 6m - 1 \Rightarrow m - n = \frac{1}{3}' class='latex' /><br />
<img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle+%5Cfrac%7B1%7D%7B3%7D+%5Cnotin+%5Cmathbb%7BN%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\displaystyle \frac{1}{3} \notin \mathbb{N}' title='\displaystyle \frac{1}{3} \notin \mathbb{N}' class='latex' /><br />
<img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle+%5Ctherefore+%5Cnot+%5Cexists+u%2C+v%2C+w+%5Cin+%5Cmathbb%7BP%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\displaystyle \therefore \not \exists u, v, w \in \mathbb{P}' title='\displaystyle \therefore \not \exists u, v, w \in \mathbb{P}' class='latex' /></p>
<blockquote><p>
There are 4 women who want to cross a bridge. They all begin on the same side. You have 17 minutes to get all of them across to the other side. It is night. There is one flashlight. A maximum of two people can cross at one time. Any party who crosses, either 1 or 2 people, must have the flashlight with them. The flashlight must be walked back and forth, it cannot be thrown, etc. Each woman walks at a different speed. A pair must walk together at the rate of the slower woman&#8217;s pace.</p>
<p>For example if Woman 1 and Woman 4 walk across first, 10 minutes have elapsed when they get to the other side of the bridge. If Woman 4 then returns with the flashlight, a total of 20 minutes have passed and you have failed the mission. What is the order required to get all women across in 17 minutes? Now, what&#8217;s the other way?
</p></blockquote>
<p>One way:</p>
<ol>
<li>Woman 1 and 2 Cross, woman 1 returns. 3 minutes total.
<li>
<li>Woman 3 and 4 Cross, woman 2 returns. 15 minutes total.</li>
<li>Woman 1 and 2 Cross. 17 Minutes total.</li>
</ol>
<p>Other way:</p>
<ol>
<li>Woman 1 and 2 Cross, woman 2 returns. 4 minutes total.
<li>
<li>Woman 3 and 4 Cross, woman 1 returns. 11 minutes total.</li>
<li>Woman 1 and 2 Cross. 17 minutes total.</li>
</ol>
<blockquote><p>
If you had an infinite supply of water and a 5 quart and 3 quart pail, how would you measure exactly 4 quarts?
</p></blockquote>
<ol>
<li>Fill 5 quart pail with 5 quarts of water from source.</li>
<li>Fill 3 quart pail with 3 quarts of water from 5 quart pail.</li>
<li>Empty 3 quart pail.</li>
<li>Empty 5 quart pail containing 2 quarts of water into 3 quart pail.</li>
<li>Fill 5 quart pail with 5 quarts of water from source.</li>
<li>Fill 3 quart pail with water from 5 quart pail.</li>
<li>5 quart pail now contains 4 quarts of water.</li>
</ol>
<blockquote><p>
Suppose you have an array of 1001 integers. The integers are in random order, but you know each of the integers is between 1 and 1000 (inclusive). In addition, each number appears only once in the array, except for one number, which occurs twice. Assume that you can access each element of the array only once. Describe an algorithm to find the repeated number. If you used auxiliary storage in your algorithm, can you find an algorithm that does not require it?
</p></blockquote>
<p><img src='http://l.wordpress.com/latex.php?latex=f%28A%29+%3D+%5Cdisplaystyle%5Csum_%7Bk+%3D+0%7D%5E%7B%7CA%7C+-+1%7D+A_%7Bk%7D+-%5Cfrac%7B%7CA%7C%28%7CA%7C-1%29%7D%7B2%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='f(A) = \displaystyle\sum_{k = 0}^{|A| - 1} A_{k} -\frac{|A|(|A|-1)}{2}' title='f(A) = \displaystyle\sum_{k = 0}^{|A| - 1} A_{k} -\frac{|A|(|A|-1)}{2}' class='latex' /></p>
<pre class="brush: csharp;">
public int duplicateNumber(int[] A) {
	int count = 0;
	for(int k = 0; k &lt; A.Length; k++)
		count += A[k];
	return count - (A.Length * (A.Length - 1) &gt;&gt; 1);
}
</pre>
<blockquote><p>
Count the number of set bits in a number. Now optimize for speed. Now optimize for size.
</p></blockquote>
<p><img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle+%5Ctext%7BLet+%7D+m+%3D+%5Csum_%7Bk+%3D+0%7D%5E%7B%5Cinfty%7D+A_%7Bk%7D+2%5E%7Bk%7D%2C+A_%7Bk%7D+%5Cin+%5B0%2C1%5D%2C+m+%5Cin+%5Cmathbb%7BN%7D_%7B0%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\displaystyle \text{Let } m = \sum_{k = 0}^{\infty} A_{k} 2^{k}, A_{k} \in [0,1], m \in \mathbb{N}_{0}' title='\displaystyle \text{Let } m = \sum_{k = 0}^{\infty} A_{k} 2^{k}, A_{k} \in [0,1], m \in \mathbb{N}_{0}' class='latex' /><br />
<img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle+f%28n%29+%3D+%5Csum_%7Bk%3D0%7D%5E%7B%5Cinfty%7DA_%7Bk%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\displaystyle f(n) = \sum_{k=0}^{\infty}A_{k}' title='\displaystyle f(n) = \sum_{k=0}^{\infty}A_{k}' class='latex' /><br />
<img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle+f%28n%29+%3D+%5Cbegin%7Bcases%7D+%5Cleft%28+n+-+n+%5Coslash+2+%5Cright%29+%2B+f%5Cleft%28+n+%5Coslash+2+%5Cright%29+%26+n+%5Cneq+0+%5C%5C+0+%26+%5Ctext%7Botherwise%7D+%5Cend%7Bcases%7D&#038;bg=fff&#038;fg=1c1c1c&#038;s=0' alt='\displaystyle f(n) = \begin{cases} \left( n - n \oslash 2 \right) + f\left( n \oslash 2 \right) &amp; n \neq 0 \\ 0 &amp; \text{otherwise} \end{cases}' title='\displaystyle f(n) = \begin{cases} \left( n - n \oslash 2 \right) + f\left( n \oslash 2 \right) &amp; n \neq 0 \\ 0 &amp; \text{otherwise} \end{cases}' class='latex' /></p>
<pre class="brush: csharp;">
public int bitsUsed(int n) {
	int count = 0;
	while(n != 0) {
		count += n &amp; 1;
		n &gt;&gt;= 1;
	}

	return count;
}
</pre>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/antimatroid.wordpress.com/68/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/antimatroid.wordpress.com/68/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/antimatroid.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/antimatroid.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/antimatroid.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/antimatroid.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/antimatroid.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/antimatroid.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/antimatroid.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/antimatroid.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/antimatroid.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/antimatroid.wordpress.com/68/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=antimatroid.wordpress.com&blog=4448583&post=68&subd=antimatroid&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://antimatroid.wordpress.com/2008/08/24/microsoft-interview-questions/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/62c32c6293d483fc7e1d545c4b9a0ac3?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">lewellen</media:title>
		</media:content>
	</item>
	</channel>
</rss>