<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" version="2.0">

<channel>
	<title>Igor Ostrovsky Blogging</title>
	
	<link>http://igoro.com</link>
	<description>On programming, technology, and random things of interest</description>
	<pubDate>Thu, 04 Jun 2009 07:52:51 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.7</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/igoro" type="application/rss+xml" /><feedburner:emailServiceId xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">igoro</feedburner:emailServiceId><feedburner:feedburnerHostname xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://feedburner.google.com</feedburner:feedburnerHostname><item>
		<title>7 tips for extending browser functionality to Silverlight apps</title>
		<link>http://igoro.com/archive/7-tips-for-extending-browser-functionality-to-silverlight-apps/</link>
		<comments>http://igoro.com/archive/7-tips-for-extending-browser-functionality-to-silverlight-apps/#comments</comments>
		<pubDate>Mon, 01 Jun 2009 07:52:06 +0000</pubDate>
		<dc:creator>Igor Ostrovsky</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://igoro.com/?p=164</guid>
		<description><![CDATA[Silverlight 2 is an awesome platform for development of rich web applications. One issue to be aware of, though, is that some browser features do not extend into Silverlight apps. For example, the Back and Forward browser buttons do not always work as the user may expect with Silverlight apps. The set of browser features [...]]]></description>
			<content:encoded><![CDATA[<p>Silverlight 2 is an awesome platform for development of rich web applications. One issue to be aware of, though, is that some browser features do not extend into Silverlight apps. For example, the Back and Forward browser buttons do not always work as the user may expect with Silverlight apps. The set of browser features you&#8217;ll miss in Silverlight apps is pretty much identical to what you&#8217;d miss in Flash or AJAX, and some of them are about to be addressed in the Silverlight 3 release.</p>
<p>Let&#8217;s go over the affected browser features one by one, and discuss ways of getting them working in Silverlight apps.</p>
<h3>Feature 1: Bookmarking and deep linking</h3>
<p><span id="more-164"></span>Users like to be able to copy the link from the address bar, email it to a friend, bookmark it, or post it on Twitter or Facebook.</p>
<p>A Silverlight app will typically transition between different views without redirecting the user to a different URL. This makes the user experience smooth and polished. As an unfortunate consequence, a user that copies the URL from the address bar or bookmarks the page will not get a link to the current active view, but instead a link to the initial view of the app.</p>
<p>Thankfully, there is a solution in Silverlight. A Silverlight app can modify the &#8220;bookmark&#8221; section of the URL, which is the part of the URL following the # character. The app can update the URL each time the user transitions to a different view, and read the bookmark on startup. See <a href="http://silverlight.net/blogs/msnow/archive/2008/09/16/silverlight-tip-of-the-day-41-using-bookmarks-in-your-silverlight-application.aspx">this article</a> for details on how to implement this.</p>
<p>The <a href="http://www.silverlightshow.net/items/The-Silverlight-3-Navigation-Framework.aspx">Navigation Framework</a> feature in the upcoming Silverlight 3 release will provide an easy-to-use solution to this problem.</p>
<h3>Feature 2: Search engine discoverability</h3>
<p>If your Silverlight app links to another page, that link is invisible to search engines. As a result, pages on your site that cannot be reached via traditional HTML links will likely not get listed in search results.</p>
<p>The solution is simple: list all pages on your site in an XML document called a Sitemap. Host the Sitemap on your site, and submit the Sitemap link to search engines. Once you do that, the search engines should include all pages on your site in their indexes.</p>
<p>For details, see the <a href="http://en.wikipedia.org/wiki/Google_Sitemaps">Wikipedia article on Sitemaps</a>.</p>
<h3>Feature 3: Back and Forward browser buttons</h3>
<p>The Back and Forward browser buttons do not work in Silverlight apps. Switching to a different view in a Silverlight app does not insert a bookmark into the browser history, so the user can&#8217;t go to the previous view by clicking the Back button.</p>
<p>The problem is similar to the bookmarking issue (Feature 1), except that the solution is more complicated. If the Silverlight app modifies the bookmark part of the URL, the previous bookmark does not get recorded in the browser history, so the user still cannot use the Back button to return to the previous view.</p>
<p>It is in fact possible to get the Back and Forward buttons working. As of SP1 3.5, ASP.NET exposes a History Control that simplifies the solution significantly (see <a href="http://blog.webjak.net/2008/09/08/control-silverlight-by-using-browser-back-and-foward-buttons/">Control Silverlight by Using Browser Back and Forward Buttons</a>). There is a variety of solutions available online in case you are not using ASP.NET 3.5 SP1, but beware that they typically involve hacks that don&#8217;t necessarily work in all browsers.</p>
<p>Or, you can wait until Silverlight 3, because browser history is properly handled in the Navigation Framework.</p>
<h3>Feature 4: Support of external tools (translation, accessibility, &#8230;)</h3>
<p>Automated translation, special browsers for people with disabilities, automated RSS aggregating&#8230; these are just some examples of useful tools that consume web content. These tools typically process HTML, but don&#8217;t peek inside Silverlight applications.</p>
<p>Since HTML is the standard representation of online documents, consider whether it would make sense to expose a simplified version of your content as a simple HTML page, in addition to your Silverlight application.</p>
<h3>Feature 5: Printing</h3>
<p>Silverlight does not currently have much support for printing. In Internet Explorer 7, Silverlight applications show up on the printout, but in Firefox or Safary they do not.</p>
<p>So, a Firefox or Safari user will not be able to print out the information displayed by your Silverlight application (at least not without taking screenshots, etc).</p>
<p>If you need to support printing, you can try two different solution approaches. If you only need to print content that can be represented using HTML (e.g., no Silverlight-generated charts and such), see <a href="http://jonas.follesoe.no/PrintingInSilverlight2UsingCSSAndASPNETAJAX4.aspx">this solution</a>. An alternate approach is to <a href="http://blog.galasoft.ch/archive/2008/10/10/converting-and-customizing-xaml-to-png-with-server-side-wpf.aspx">convert XAML to an image format on the server</a>.</p>
<h3>Feature 6: Open link in new tab</h3>
<p>There doesn&#8217;t seem to be a very good way to implement the &#8216;Open link in new tab&#8217; feature in Silverlight. You can use a HyperlinkButton with a Target set to _blank, which seems to open a new tab in Firefox and a new Window in IE 7. But that still won&#8217;t allow the user to choose whether to open the page in the same or different tab/window.</p>
<p>If you are committed enough, you can probably implement a HyperlinkButton with a context menu allowing the user to open the link in a new tab/window. Right-clicking is not directly supported in Silverlight, but <a href="http://silverlight.net/blogs/msnow/archive/2008/07/01/tip-of-the-day-14-how-to-right-click-on-a-silverlight-application.aspx">workarounds do exist</a>.</p>
<p>Or, use hyperlinks sparingly in Silverlight apps.</p>
<h3>Feature 7: Find on this page</h3>
<p>I use the &#8216;Find on this page&#8217; feature (CTRL+F) extensively when browsing the web. But, content inside Silverlight apps is not searched by the browser.</p>
<p>A mitigation is to carefully design the app UI in a way that minimizes the user&#8217;s need to search. Data should be sortable and searchable in various ways, and important information should be shown prominently (e.g., the user&#8217;s own position on a scoreboard should be highlighted).</p>
<p>These are all good practices regardless of your development platform, but unavailability of the &#8216;Find on this page&#8217; feature makes them even more important.</p>
<h3>Conclusion</h3>
<p>Hopefully you&#8217;ll find these points helpful when designing your next Silverlight application. If you have other tips on extending browser features into Silverlight apps, let me know in the comments!</p>
<img src="http://feeds.feedburner.com/~r/igoro/~4/lyYbeDhNFKs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://igoro.com/archive/7-tips-for-extending-browser-functionality-to-silverlight-apps/feed/</wfw:commentRss>
		</item>
		<item>
		<title>My YouTube debut: a RoboZZle demo video</title>
		<link>http://igoro.com/archive/my-youtube-debut-a-robozzle-demo-video/</link>
		<comments>http://igoro.com/archive/my-youtube-debut-a-robozzle-demo-video/#comments</comments>
		<pubDate>Fri, 01 May 2009 08:53:39 +0000</pubDate>
		<dc:creator>Igor Ostrovsky</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://igoro.com/?p=155</guid>
		<description><![CDATA[It took significantly longer than I expected, but the RoboZZle demo video is finally on YouTube.
The video made the reddit front page, so you can read the usual mixture of insightful, funny, and outright insane comments on the reddit page and the YouTube page.
My favorite funny comment is this one:

And finally, this is the video:

]]></description>
			<content:encoded><![CDATA[<p>It took significantly longer than I expected, but the RoboZZle demo video is finally on YouTube.</p>
<p>The video made the reddit front page, so you can read the usual mixture of insightful, funny, and outright insane comments on the <a href="http://www.reddit.com/r/programming/comments/8gs5j/demo_video_of_robot_programming_game_with_user/">reddit page</a> and the <a href="http://www.youtube.com/watch?v=MmqBVWi_Pc0">YouTube page</a>.</p>
<p>My favorite funny comment is this one:<br />
<img class="alignnone size-full wp-image-159" style="border: 2px solid gray" title="silverlight_tinfoilhat1" src="http://igoro.com/wordpress/wp-content/uploads/2009/05/silverlight_tinfoilhat1.png" alt="silverlight_tinfoilhat1" width="630" height="159" /></p>
<p>And finally, this is the video:<br />
<object width="640" height="505" data="http://www.youtube.com/v/MmqBVWi_Pc0&amp;hl=en&amp;fs=1&amp;rel=0" type="application/x-shockwave-flash"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/v/MmqBVWi_Pc0&amp;hl=en&amp;fs=1&amp;rel=0" /><param name="allowfullscreen" value="true" /></object></p>
<img src="http://feeds.feedburner.com/~r/igoro/~4/D0JOcGRpUlo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://igoro.com/archive/my-youtube-debut-a-robozzle-demo-video/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Precomputed view: A cool and useful SQL pattern</title>
		<link>http://igoro.com/archive/precomputed-view-a-cool-and-useful-sql-pattern/</link>
		<comments>http://igoro.com/archive/precomputed-view-a-cool-and-useful-sql-pattern/#comments</comments>
		<pubDate>Tue, 14 Apr 2009 08:55:17 +0000</pubDate>
		<dc:creator>Igor Ostrovsky</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://igoro.com/archive/precomputed-view-a-cool-and-useful-sql-pattern/</guid>
		<description><![CDATA[In database terminology, a view is a named query that typically aggregates data from multiple tables. When using views, it is important to remember that querying a view will evaluate the query that defines the view. Repeated evaluation of the view - say from within a nested query - may seriously impact or even kill [...]]]></description>
			<content:encoded><![CDATA[<p>In database terminology, a view is a named query that typically aggregates data from multiple tables. When using views, it is important to remember that querying a view will evaluate the query that defines the view. Repeated evaluation of the view - say from within a nested query - may seriously impact or even kill the performance of your application.</p>
<p>One solution to this performance problem is to use a &#8220;precomputed view&#8221;. Unlike an ordinary view, a precomputed view is stored in a table rather than computed on demand. When data in one of the aggregated tables changes, the update operation also updates the precomputed view table.</p>
<p><span id="more-137"></span></p>
<p>A great thing about precomputed views is that they can be implemented fully in SQL. Any code that accesses the database sees a precomputed view as a regular table. Also, if you have an existing regular view, you can change it into a precomputed view without having to modify any code that queries the view.</p>
<p>To explain the precomputed view pattern, let&#8217;s look at an example loosely inspired by the <a href="http://reddit.com/">reddit</a> social news site. Users submit articles to reddit and the articles receive up and down votes from other users. User&#8217;s &#8220;karma&#8221; is computed as a sum of votes on positively-voted articles submitted by the user.</p>
<p>To store the reddit data, you can store users in one table, articles in another table, and votes (+1 or -1) from users on articles in a third table:</p>
<p><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="251" alt="image" src="/wordpress/wp-content/uploads/2009/04/image.png" width="513" border="0"> </p>
<p>Now, say that we want to find the top 10 users with highest karma. To compute a user&#8217;s karma, we need to sum up the scores of all articles submitted by the user. And to compute each article score, we need to aggregate the votes for that article. It should be clear that this query is going to be very expensive, no matter how much you tune and optimize it.</p>
<p>Views could be used to factor the complex query into simpler pieces, but not to decrease its overall cost:</p>
<p><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="410" alt="image" src="/wordpress/wp-content/uploads/2009/04/image1.png" width="513" border="0">&nbsp;</p>
<p>It is easy to find the top 10 users, simply by querying User_View. Unfortunately, if the database contains millions and millions of votes, the query will take a long time to run. The query will have to group all votes by article, group all articles by user, and then pick the top users. Imagine the impact on performance if you wanted to show the top users on every page of your web app!</p>
<p>However, by changing the views into precomputed views, we can make the query for top users cheap:</p>
<p><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="425" alt="image" src="/wordpress/wp-content/uploads/2009/04/image2.png" width="572" border="0">&nbsp; </p>
<p>Let&#8217;s walk through the conversion of Article_View to a precomputed view. First, we&#8217;ll create a table for the precomputed view:
<pre class="code"><span style="color: blue">    CREATE TABLE </span>Article_PView<span style="color: gray">(
        </span>ArticleId <span style="color: blue">int </span><span style="color: gray">NOT NULL,
        </span>Title <span style="color: blue">varchar</span><span style="color: gray">(</span>40<span style="color: gray">) NOT NULL,
        </span>Url <span style="color: blue">varchar</span><span style="color: gray">(</span>250<span style="color: gray">) NOT NULL,
        </span>VoteSum <span style="color: blue">int </span><span style="color: gray">NOT NULL,
    )
</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Second, we&#8217;ll need two triggers. This trigger inserts a row into Article_PView whenever a new row is inserted into the Article table:
<pre class="code"><span style="color: blue">    CREATE TRIGGER </span>TRG_ArticleInsert
        <span style="color: blue">ON  </span>Article
        <span style="color: blue">AFTER INSERT
    AS
    BEGIN
        SET NOCOUNT ON</span><span style="color: gray">;

        </span><span style="color: blue">INSERT INTO </span>Article_PView <span style="color: gray">(</span>ArticleId<span style="color: gray">, </span>Title<span style="color: gray">, </span>Url<span style="color: gray">, </span>VoteSum<span style="color: gray">)
        </span><span style="color: blue">SELECT </span>Id <span style="color: blue">As </span>ArticleId<span style="color: gray">, </span>Title<span style="color: gray">, </span>Url<span style="color: gray">, </span>0
        <span style="color: blue">FROM </span>Inserted
<span style="color: blue">    END</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>And this trigger recomputes a row in Article_PView whenever a vote is inserted, updated or deleted:
<pre class="code"><span style="color: blue">    CREATE TRIGGER </span>TRG_Vote
        <span style="color: blue">ON  </span>Vote
        <span style="color: blue">AFTER INSERT</span><span style="color: gray">, </span><span style="color: blue">UPDATE</span><span style="color: gray">, </span><span style="color: blue">DELETE
    AS
    BEGIN
        SET NOCOUNT ON</span><span style="color: gray">;

        </span><span style="color: blue">WITH </span>articleIds<span style="color: gray">(</span>ArticleId<span style="color: gray">) </span><span style="color: blue">As
        </span><span style="color: gray">(
            </span><span style="color: blue">SELECT </span>ArticleId <span style="color: blue">From </span>Inserted
            <span style="color: blue">UNION
            SELECT </span>ArticleId <span style="color: blue">From </span>Deleted
        <span style="color: gray">)
        </span><span style="color: blue">UPDATE </span>Article_PView
            <span style="color: blue">SET </span>VoteSum <span style="color: gray">= (
                </span><span style="color: blue">SELECT </span><span style="color: magenta">SUM</span><span style="color: gray">(</span>Vote<span style="color: gray">) </span><span style="color: blue">FROM </span>Vote
                <span style="color: blue">WHERE </span>Article_PView<span style="color: gray">.</span>ArticleId <span style="color: gray">= </span>articleIds<span style="color: gray">.</span>ArticleId<span style="color: gray">)
        </span><span style="color: blue">FROM </span>articleIds
        <span style="color: blue">WHERE </span>Article_PView<span style="color: gray">.</span>ArticleId <span style="color: gray">= </span>articleIds<span style="color: gray">.</span>ArticleId
<span style="color: blue">    END</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>And finally, we&#8217;ll populate the precomputed view with data that is already in the database:
<pre class="code"><span style="color: blue">    INSERT INTO </span>Article_PView <span style="color: gray">(</span>ArticleId<span style="color: gray">, </span>Title<span style="color: gray">, </span>Url<span style="color: gray">, </span>VoteSum<span style="color: gray">)
</span><span style="color: blue">    SELECT </span>Article<span style="color: gray">.</span>Id<span style="color: gray">, </span>Title<span style="color: gray">, </span>Url<span style="color: gray">, </span><span style="color: magenta">ISNULL</span><span style="color: gray">((</span><span style="color: blue">SELECT </span><span style="color: magenta">SUM</span><span style="color: gray">(</span>vote<span style="color: gray">) </span><span style="color: blue">FROM </span>Vote <span style="color: blue">WHERE </span>ArticleId <span style="color: gray">= </span>Article<span style="color: gray">.</span>Id<span style="color: gray">), </span>0<span style="color: gray">)
</span><span style="color: blue">    FROM </span>Article</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Article_PView precomputed view is now ready, and User_PView can be created in a similar fashion. </p>
<p><strong>Remarks</strong> </p>
<p>Note that my example assumes articles never get removed or updated. Adding support for that functionality is straightforward: you&#8217;ll need to extend the TRG_ArticleInsert trigger to also handle updates and deletes. This will be very similar to what TRG_Vote does, but I left it out from the sample for simplicity.
</p>
<p>There are several interesting variations of how Article_PView could be implemented. In the implementation above, the trigger aggregates the votes for an article each time someone votes on it. If you want to avoid this cost, you can change the trigger so that it only adjusts the article score instead of recomputing it. For example, if a vote was updated from -1 to +1, the trigger would add 2 to the score of the article. Avoiding concurrency issues may be tricky with that approach, though.</p>
<p>Another interesting variation is adding the VoteSum column to the Article table instead of creating a separate table. Choose the approach that better fits your table design.</p>
<p>Hope you find this pattern useful!</p>
<img src="http://feeds.feedburner.com/~r/igoro/~4/k8LgfH3U2NY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://igoro.com/archive/precomputed-view-a-cool-and-useful-sql-pattern/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Choose expression: proposal for a revolutionary C# construct</title>
		<link>http://igoro.com/archive/choose-expression-proposal-for-a-revolutionary-c-construct/</link>
		<comments>http://igoro.com/archive/choose-expression-proposal-for-a-revolutionary-c-construct/#comments</comments>
		<pubDate>Wed, 01 Apr 2009 09:04:36 +0000</pubDate>
		<dc:creator>Igor Ostrovsky</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://igoro.com/?p=122</guid>
		<description><![CDATA[Notice that this post was published on April 1, 2009.
For decades, computer science students have been taught that so-called NP-hard problems do not have known efficient solutions. These problems include the infamous Travelling salesman problem, subset sum, 3SAT, and many more.
But - as is often the case - where theoretical Computer Science failed, sound software [...]]]></description>
			<content:encoded><![CDATA[<p><span style="color: #ff0000;">Notice that this post was published on <strong>April 1</strong>, 2009.</span></p>
<p>For decades, computer science students have been taught that so-called NP-hard problems do not have known efficient solutions. These problems include the infamous <a href="http://en.wikipedia.org/wiki/Travelling_salesman_problem">Travelling salesman problem</a>, <a href="http://en.wikipedia.org/wiki/Subset_sum">subset sum</a>, <a href="http://en.wikipedia.org/wiki/3SAT">3SAT</a>, and many more.</p>
<p>But - as is often the case - where theoretical Computer Science failed, sound software engineering practices will succeed. By using loosely-coupled OOP, agile methodologies and the model-view-controller architectural pattern, I developed a solution that someone trapped in the world of formulas and big Ohs would never dream of.</p>
<p>Enough with the background, and let&#8217;s take a deep dive into the intriguing design.<br />
<span id="more-122"></span><br />
<strong>Introducing the choose expression</strong></p>
<p>As most other elegant designs, this one is very simple. My proposal calls for a choose expression with this syntax:</p>
<pre class="code">    <span style="color: blue">choose </span>{ boolean_expression1, boolean_expression2 }</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Choose expression is basically the || operator, only with a slight twist. The semantics of the choose expression are similarly simple:</p>
<ol>
<li>If boolean_expression1 or boolean_expression2 will evaluate to true, the runtime will evaluate the true expression, but not the other expression. The return value of the choose expression will be true in this case.</li>
<li>If both expressions will evaluate to false, the runtime will evaluate neither expression. The return value of the choose expression is false in this case.</li>
</ol>
<p>Let&#8217;s look at a few simple usage examples:</p>
<pre class="code"><span style="color: blue">    bool </span>a = <span style="color: blue">choose </span>{
        1 == 2,
        1 &lt; 2
    };</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Variable a will be set to true, because the condition 1 &lt; 2 is true.</p>
<p>Here is another example:</p>
<pre class="code"><span style="color: blue">    bool </span>a = <span style="color: blue">choose </span>{
        ((<span style="color: #2b91af">Func</span>&lt;<span style="color: blue">bool</span>&gt;)(() =&gt; { <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"Hello"</span>); <span style="color: blue">return false</span>; }))(),
        1 &lt; 2
    };</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>There is no point executing the first function, because it would return false anyways. So, this code sample does not print anything to screen. Instead, the choose expression will execute the second function. The second expression returns true, so variable a will be set to true.</p>
<p>And another simple one:</p>
<pre class="code"><span style="color: blue">    bool </span>a = <span style="color: blue">choose </span>{
        ((<span style="color: #2b91af">Func</span>&lt;<span style="color: blue">bool</span>&gt;)(() =&gt; { <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"Hello1"</span>); <span style="color: blue">return false</span>; })(),
        ((<span style="color: #2b91af">Func</span>&lt;<span style="color: blue">bool</span>&gt;)(() =&gt; { <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"Hello2"</span>); <span style="color: blue">return false</span>; })(),
    };</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>This code sample will not be print anything to screen either. It is obvious; why evaluate either of the two functions if they are going to return false anyways? This code simply assigns false to variable a.</p>
<p>Now, let&#8217;s cut to the chase, and use choose expressions to give an efficient implementation of an NP-hard problem. Let&#8217;s look at subset sum:</p>
<pre class="code"><span style="color: blue">    bool </span>SubsetSum(<span style="color: blue">int</span>[] arr)
    {
        <span style="color: blue">return </span>SubsetSumHelper(arr, 0, 0);
    }

<span style="color: blue">    bool </span>SubsetSumHelper(<span style="color: blue">int</span>[] arr, <span style="color: blue">int </span>index, <span style="color: blue">int </span>sumSoFar)
    {
        <span style="color: blue">if </span>(index == arr.Length)
        {
            <span style="color: blue">return </span>sumSoFar == 0;
        }

        <span style="color: blue">return </span><span style="color: blue">choose</span> {
            () =&gt; SubsetSumHelper(arr, index + 1, sumSoFar + arr[index]),
            () =&gt; SubsetSumHelper(arr, index + 1, sumSoFar)
        };
    }</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Yes, that&#8217;s right! An O(N) implementation of the subset sum problem. There you have it, computer scientists. You said it was impossible. If anyone at the University of British Columbia needs my mailing address to send me a refund check for my education, you can find my contact information in the margin.</p>
<p><strong>Under the hood of the choose expression</strong></p>
<p>After a couple hours of coding, I was able to develop a simple prototype. It works perfectly, but since it is only a prototype, I simplified my life a little bit by allowing choose to execute both functions. After all, I don&#8217;t have to slave through all the nitty-gritty details in the initial prototype, right? The performance of my implementation is not that great either, but I haven&#8217;t had the time to fire up the profiler so far. Perhaps I need to unroll a loop somewhere, or ensure that method calls are getting inlined optimally.</p>
<p>To further prove the feasibility of my design, I developed a <a href="http://en.wikipedia.org/wiki/Non-deterministic_turing_machine">non-deterministic Turing machine</a> construction that evaluates choose expressions extremely efficiently.</p>
<p>Non-deterministic Turing machines are known to be a good realistic abstraction of computing hardware; there was a study that proved that. To be exact, the study was only a moderate success. The researchers built a mechanical non-deterministic Turing machine that solved a Travelling Salesperson problem with 5 cities without a hitch. On the 6-city version of the problem, the experiment had to be abruptly interrupted after sprawling machine replicas filled up the room, and the head of one of the researchers got caught in a loop of tape.</p>
<p>So, it is clear that this design is sound. There may be performance issues in the first release, but they will improve as the technology matures. And once CPU manufacturers include a non-deterministic branching instruction in the instruction set, the cost of evaluating the choose expression will drop down to a couple of instructions.</p>
<p><strong>Summary</strong></p>
<p>I don&#8217;t know the detailed plans surrounding the C# language, but if there is a C# 4.1., I would like to see the choose expression included.</p>
<p>And the larger lesson of this post is simple: computer science is largely obsolete in today&#8217;s world of technology. Computer science says that this is impossible, that is impossible&#8230; As you just saw, anything is possible, so long as you have enough paper to print out all the UML diagrams.</p>
<img src="http://feeds.feedburner.com/~r/igoro/~4/47cNe1oefik" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://igoro.com/archive/choose-expression-proposal-for-a-revolutionary-c-construct/feed/</wfw:commentRss>
		</item>
		<item>
		<title>The first month of my online game</title>
		<link>http://igoro.com/archive/the-first-month-of-my-online-game/</link>
		<comments>http://igoro.com/archive/the-first-month-of-my-online-game/#comments</comments>
		<pubDate>Mon, 23 Mar 2009 10:47:15 +0000</pubDate>
		<dc:creator>Igor Ostrovsky</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://igoro.com/?p=112</guid>
		<description><![CDATA[It&#8217;s now been a month since I launched RoboZZle, so it is a good time to reflect on how things went so far. It has been a great experience, and the project took up all of my free time and then some.
For fun, I&#8217;ll discuss different aspects of RoboZZle and assign each a letter grade.
Game [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft" style="margin: 10px;" src="http://igoro.com/wordpress/wp-content/uploads/2009/03/robozzle_image.png" alt="" align="left" />It&#8217;s now been a month since I <a href="http://igoro.com/archive/my-hobby-project-a-social-puzzle-game-developed-in-silverlight/">launched</a> <a href="http://robozzle.com/">RoboZZle</a>, so it is a good time to reflect on how things went so far. It has been a great experience, and the project took up all of my free time and then some.</p>
<p>For fun, I&#8217;ll discuss different aspects of RoboZZle and assign each a letter grade.</p>
<p><strong>Game Addictiveness: A</strong><br />
<span id="more-112"></span><br />
Let&#8217;s start with the positive. RoboZZle has shown to be an addictive game, at least for a certain audience. There is a core group of players that log in regularly, solve puzzles, participate in discussions, design puzzles, propose improvements, and so forth.</p>
<p>A great illustration of my point is a quote from player <a href="http://robozzle.com/user.aspx?name=recursive">recursive</a> after finally cracking a long unsolved <a href="http://robozzle.com/puzzle.aspx?id=102">puzzle</a> designed by <a href="http://robozzle.com/user.aspx?name=evko">evko</a>:</p>
<blockquote><p>This level is amazing.</p>
<p>I spent about 6 hours solving this one. It took me a while to realize that every movement had to be saved on a stack. Then I developed diagrams, models, and a logical structure around it. And eventually stumbled my way to the solution logically. But it all seems so intuitively obvious now.</p>
<p>This is the best level I&#8217;ve solved so far. Bravo.</p></blockquote>
<p>RoboZZle players have contributed in a variety of ways:</p>
<ul>
<li><a href="http://robozzle.com/user.aspx?name=aalku">aalku</a> contributed articles to a number of sections of the <a href="http://robozzle.com/wiki/">wiki</a> (still in an early stage).</li>
<li><a href="http://robozzle.com/user.aspx?name=evko">evko</a> is a brilliant puzzle designer who created 42 puzzles, many of them amazingly clever and innovative.</li>
<li><a href="http://robozzle.com/user.aspx?name=hr0nix">hr0nix</a> implemented an <a href="http://code.google.com/p/robozzlesolver/">automated solver</a> for simpler RoboZZle puzzles.</li>
<li><a href="http://robozzle.com/user.aspx?name=life96">life96</a> made a number of helpful suggestions, and investigated the CPU usage of the game.</li>
<li><a href="http://robozzle.com/user.aspx?name=stingray">stingray</a> blogged about RoboZZle. The article <a href="http://www.genericerror.com/blog/2009/02/27/CanGamesTeachYouToProgram.aspx">Can Games Teach You To Program?</a> got popular on reddit.</li>
<li><a href="http://robozzle.com/user.aspx?name=recursive">recursive</a> has an amazingly deep understanding of the game, and discovered shortest known solution for nearly all puzzles.</li>
</ul>
<p>Finally, I really like this comment left by player <a href="http://robozzle.com/user.aspx?name=spikeless">spikeless</a> the day that RoboZZle launched:</p>
<blockquote><p>Brilliant game! It has seriously impacted productivity in our development team leaving nothing to be heard but frustrated curses and elated ‘Yesss’s.</p></blockquote>
<p>For addictiveness, I give RoboZZle a shameless A.</p>
<p><strong>Features: B</strong></p>
<p>My approach has been to do the minimal set of features I can get away with (but no less), and then grow the game from there. Otherwise, I would still be only 50% done; or more likely, I&#8217;d have given up a long time ago.</p>
<p>Since the game launched, I&#8217;ve been furiously adding features, in part driven by user feedback, and in part based on what I think will make the game work better.</p>
<p>I added <a href="http://robozzle.com/forums">forums</a>, <a href="http://robozzle.com/blog/?p=9">RSS feed for puzzles</a>, <a href="http://robozzle.com/wiki">wiki</a>, <a href="http://robozzle.com/forums">scoreboard for shortest solutions</a>, <a href="http://robozzle.com/blog/?p=14">a stepping debugger for solutions</a>, <a href="http://robozzle.com/forums/thread.aspx?id=168">a new game mode</a>, and lots more.</p>
<p>I give RoboZZle a B here because there are so many more things that I want to do with the game. I can already tell that this will keep me busy for a good while. <img src='http://igoro.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p><strong>Code Quality: B-</strong></p>
<p>This section is about bugs! Similarly to features, I tried to make things &#8220;good enough&#8221;, and then deploy. Otherwise, I would never get anything done.</p>
<p>Most of the time, this worked fine. Only once a new feature introduced a major bug that impacted the game play for a lot of users. That time, the robot would sometimes seriously misbehave, e.g. continuing its path even though it should have died by falling off a tile.</p>
<p>Except for this one instance, most bugs have been minor issues that most players won&#8217;t run into. There are a few minor blemishes still present in the game, but I&#8217;m working my way through them.</p>
<p>So, it seems appropriate that RoboZZle gets a B- for quality.</p>
<p><strong>Incoming Traffic: C+</strong></p>
<p>Hmm&#8230; incoming traffic. While the loyalty of visitors seems to be great, the incoming traffic numbers aren&#8217;t quite as impressive. This table gives a quick summary:</p>
<table border="0" cellspacing="0" cellpadding="2" width="400">
<tbody>
<tr>
<td width="286" valign="top">Visits</td>
<td width="112" valign="top">23,000</td>
</tr>
<tr>
<td width="286" valign="top">Absolute Unique Visitors</td>
<td width="112" valign="top">12,754</td>
</tr>
<tr>
<td width="286" valign="top">Registered Players</td>
<td width="112" valign="top">1,379</td>
</tr>
<tr>
<td width="286" valign="top">Registered Players with 10+ puzzles solved</td>
<td width="112" valign="top">877</td>
</tr>
</tbody>
</table>
<p>23,000 visits is nothing to sneeze at, but I&#8217;ve seen similar numbers for  a blog post that took me a weekend to write. (In all fairness, most of those visitors probably spent less than a second &#8220;reading&#8221; my blog post.)</p>
<p>Here are the main sources of incoming traffic for robozzle.com:</p>
<table border="0" cellspacing="0" cellpadding="2" width="400">
<tbody>
<tr>
<td width="200" valign="top"><strong>Domain</strong></td>
<td width="200" valign="top"><strong>Visits</strong></td>
</tr>
<tr>
<td width="200" valign="top"><a href="http://silverlight.net/">silverlight.net</a></td>
<td width="200" valign="top">4,013</td>
</tr>
<tr>
<td width="200" valign="top"><a href="http://habrahabr.ru">habrahabr.ru</a></td>
<td width="200" valign="top">1,826</td>
</tr>
<tr>
<td width="200" valign="top"><a href="http://google.com">google.com</a></td>
<td width="200" valign="top">1,366</td>
</tr>
<tr>
<td width="200" valign="top"><a href="http://dotnetkicks.com">dotnetkicks.com</a></td>
<td width="200" valign="top">839</td>
</tr>
<tr>
<td width="200" valign="top"><a href="http://genericerror.com">genericerror.com</a></td>
<td width="200" valign="top">779</td>
</tr>
<tr>
<td width="200" valign="top"><a href="http://bluebytesoftware.com">bluebytesoftware.com</a></td>
<td width="200" valign="top">348</td>
</tr>
</tbody>
</table>
<p>So, it&#8217;s silverlight.net, some popular Russian site, google, dotnetkicks, and two blogs (both recommended reading). Other than that, there are many sources that contribute a small number of visitors each.</p>
<p>I should be able to do better. A part of the problem is that most people still don&#8217;t have Silverlight installed, and Silverlight gaming is in its infancy. There are signs that this is about to improve, such as <a href="http://mashooo.com">http://mashooo.com</a>, <a href="http://silverarcade.com">http://silverarcade.com</a> and <a href="http://silverlightclub.com">http://silverlightclub.com</a>, so I&#8217;m keeping my fingers crossed.</p>
<p>The other part of the problem is that I need to learn how to better market RoboZZle and draw in visitors. This is a new territory for me, but I&#8217;m learning new things every day.</p>
<p>And that&#8217;s the main reason I&#8217;m working on RoboZZle, so it&#8217;s OK. <img src='http://igoro.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<img src="http://feeds.feedburner.com/~r/igoro/~4/hwTl7-yIcKI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://igoro.com/archive/the-first-month-of-my-online-game/feed/</wfw:commentRss>
		</item>
		<item>
		<title>My hobby project: a social puzzle game developed in Silverlight</title>
		<link>http://igoro.com/archive/my-hobby-project-a-social-puzzle-game-developed-in-silverlight/</link>
		<comments>http://igoro.com/archive/my-hobby-project-a-social-puzzle-game-developed-in-silverlight/#comments</comments>
		<pubDate>Sun, 22 Feb 2009 05:07:12 +0000</pubDate>
		<dc:creator>Igor Ostrovsky</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://igoro.com/archive/my-hobby-project-a-social-puzzle-game-developed-in-silverlight/</guid>
		<description><![CDATA[After about 3 months of evening coding, the game that I&#8217;ve been working on is now live.
RoboZZle is an online puzzle game that challenges you to program a robot to pick up all stars on a game board. The game mechanics are simple, yet allow for a wide variety of challenges that call for very [...]]]></description>
			<content:encoded><![CDATA[<p>After about 3 months of evening coding, the game that I&#8217;ve been working on is now <a href="http://robozzle.com/">live</a>.</p>
<p><a href="http://robozzle.com/">RoboZZle</a> is an online puzzle game that challenges you to program a robot to pick up all stars on a game board. The game mechanics are simple, yet allow for a wide variety of challenges that call for very different solution approaches.</p>
<p>Here is an example of a solved RoboZZle puzzle, with the arrow edited-in to show the path of the robot:</p>
<p><span id="more-96"></span>
<p><a href="http://igoro.com/wordpress/wp-content/uploads/2009/02/robozzle-puzzle.jpg"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="179" alt="robozzle_puzzle" src="http://igoro.com/wordpress/wp-content/uploads/2009/02/robozzle-puzzle-thumb.jpg" width="244" border="0"></a> </p>
<p>&nbsp;</p>
<p>Since designing RoboZZle puzzles is as much fun as solving them, the game includes a tool to make puzzles yourself. After you create a puzzle, you submit it, and other players will get an opportunity to try to solve it.</p>
<p>In this screenshot, I am just about done designing a challenging puzzle:</p>
<p><a href="http://igoro.com/wordpress/wp-content/uploads/2009/02/robozzle-designer.jpg"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="147" alt="robozzle_designer" src="http://igoro.com/wordpress/wp-content/uploads/2009/02/robozzle-designer-thumb.jpg" width="244" border="0"></a> </p>
<p>&nbsp;</p>
<p>Players rate the difficulty of each puzzle, as well as vote whether they liked it or not. When looking for the next puzzle to solve, players can use the ratings to find cool puzzles with the difficulty that suits their current mood.</p>
<p>This screenshot shows the main RoboZZle page at <a href="http://robozzle.com">http://robozzle.com</a>:</p>
<p><a href="http://igoro.com/wordpress/wp-content/uploads/2009/02/robozzle-main.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="175" alt="robozzle_main" src="http://igoro.com/wordpress/wp-content/uploads/2009/02/robozzle-main-thumb.png" width="244" border="0"></a>&nbsp;</p>
<p>&nbsp;</p>
<p>Players can lookup their ranking, as well as statistics on all players and puzzles on the <a href="http://www.robozzle.com/scoreboard.aspx">statistics pages</a>.</p>
<p><a href="http://igoro.com/wordpress/wp-content/uploads/2009/02/robozzle-stats.jpg"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="197" alt="robozzle_stats" src="http://igoro.com/wordpress/wp-content/uploads/2009/02/robozzle-stats-thumb.jpg" width="244" border="0"></a>&nbsp;</p>
<p>&nbsp;</p>
<p>In a Web 2.0 fashion, RoboZZle is designed to be a user-driven, social experience. Please <a href="http://robozzle.com/">check it out</a>, install Silverlight if you need to (it is safe to install), and let me know how you like the game.</p>
<img src="http://feeds.feedburner.com/~r/igoro/~4/_HRXNfSv51E" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://igoro.com/archive/my-hobby-project-a-social-puzzle-game-developed-in-silverlight/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Puzzling over arrays and enumerators in C#</title>
		<link>http://igoro.com/archive/puzzling-over-arrays-and-enumerators-in-c/</link>
		<comments>http://igoro.com/archive/puzzling-over-arrays-and-enumerators-in-c/#comments</comments>
		<pubDate>Mon, 02 Feb 2009 22:59:08 +0000</pubDate>
		<dc:creator>Igor Ostrovsky</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://igoro.com/archive/puzzling-over-arrays-and-enumerators-in-c/</guid>
		<description><![CDATA[Here is a little puzzle for C# developers reading my blog. What is the error in the program below?
   using System.Collections.Generic;
   class Program
   {
       public static void Main()
       {
         [...]]]></description>
			<content:encoded><![CDATA[<p>Here is a little puzzle for C# developers reading my blog. What is the error in the program below?</p>
<pre class="code"><span style="color: blue">   using </span>System.Collections.Generic;
<span style="color: blue"></span><span style="color: blue">   class </span><span style="color: #2b91af">Program
</span>   {
       <span style="color: blue">public static void </span>Main()
       {
           <span style="color: blue">int</span>[] arr = <span style="color: blue">new int</span>[10];
           <span style="color: #2b91af">IEnumerator</span>&lt;<span style="color: blue">int</span>&gt; e = arr.GetEnumerator();
       }
   }</pre>
<p>If you don&#8217;t see it, don&#8217;t worry.&nbsp; I was surprised by this C# behavior as well. Just come back in a couple days to see the solution. Or try to compile the program in Visual Studio. <img src='http://igoro.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>PS.: The cause for the low cadency of posts on my blog is a side project (an online game written in Silverlight) that has been draining away my extra time over the last few months. Expect an announcement in two to three weeks, once it&#8217;s ready for launch.</p>
<img src="http://feeds.feedburner.com/~r/igoro/~4/9ga1YTBv9HA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://igoro.com/archive/puzzling-over-arrays-and-enumerators-in-c/feed/</wfw:commentRss>
		</item>
		<item>
		<title>How to recover a lost post in Windows Live Writer</title>
		<link>http://igoro.com/archive/how-to-recover-a-lost-post-in-windows-live-writer/</link>
		<comments>http://igoro.com/archive/how-to-recover-a-lost-post-in-windows-live-writer/#comments</comments>
		<pubDate>Wed, 19 Nov 2008 07:16:53 +0000</pubDate>
		<dc:creator>Igor Ostrovsky</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://igoro.com/?p=84</guid>
		<description><![CDATA[Windows Live Writer is an awesome tool that I use to write all of my blog posts. I am so used to it that I can&#8217;t imagine blogging without it, but I have also found ways to shoot myself in the foot with it. Here are two ways in which I managed to lose a [...]]]></description>
			<content:encoded><![CDATA[<p>Windows Live Writer is an awesome tool that I use to write all of my blog posts. I am so used to it that I can&#8217;t imagine blogging without it, but I have also found ways to shoot myself in the foot with it. Here are two ways in which I managed to lose a nearly finished blog post:</p>
<ol>
<li>Live Writer clears its undo history when you switch between views. So, if you mess up your article in the HTML view, you won&#8217;t be able to revert the change when you notice the disaster after switching back into the Normal view.
<li>In the Preview view, Live Writer looks a lot like Internet Explorer. If you are not careful, it is not too hard to close Live Writer by accident. And, the confirmation dialog looks somewhat like IE&#8217;s closing dialog.</li>
</ol>
<p>Thankfully, I found a way to recover Live Writer posts, and saved myself some wasted work.</p>
<p><span id="more-84"></span></p>
<p>Every time you switch Live Writer to the Preview or the Normal View, a copy of the post will be written as a HTML file into a temporary directory. On my machine, each snapshot is saved under C:\Users\Igor\AppData\Local\Temp\WindowsLiveWriter1286139640:</p>
<p>&nbsp;</p>
<p>&nbsp;<img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="600" alt="image" src="http://igoro.com/wordpress/wp-content/uploads/2008/11/image.png" width="703" border="0"> </p>
<p>&nbsp;</p>
<p>Sorting the snapshots by &#8216;Date modified&#8217; column gives you the history of your edits, so long as you regularly switch between the different views in Live Writer.</p>
<p>With a bit of luck, you will find the right version of the lost article somewhere among the snapshots.</p>
<img src="http://feeds.feedburner.com/~r/igoro/~4/fUDO3qBHTl4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://igoro.com/archive/how-to-recover-a-lost-post-in-windows-live-writer/feed/</wfw:commentRss>
		</item>
		<item>
		<title>How to write a self-printing program</title>
		<link>http://igoro.com/archive/how-to-write-a-self-printing-program/</link>
		<comments>http://igoro.com/archive/how-to-write-a-self-printing-program/#comments</comments>
		<pubDate>Fri, 31 Oct 2008 16:46:38 +0000</pubDate>
		<dc:creator>Igor Ostrovsky</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://igoro.com/archive/how-to-write-a-self-printing-program/</guid>
		<description><![CDATA[As promised at the end of my recent post, I am going to explain how to implement a program that prints itself, in addition to doing other things (like playing Game of Life).
A self-printing program - also called a quine - is a program that prints out its own source code. I will describe one [...]]]></description>
			<content:encoded><![CDATA[<p>As promised at the end of my recent <a href="http://igoro.com/archive/self-printing-game-of-life-in-c">post</a>, I am going to explain how to implement a program that prints itself, in addition to doing other things (like playing Game of Life).</p>
<p>A self-printing program - also called a quine - is a program that prints out its own source code. I will describe one simple way to implement a quine that can be adapted to just about any programming language. The technique does not depend on any unusual language features, but also does not necessarily yield the shortest possible quine in a particular language.</p>
<p>The main idea behind this quine implementation is simple. The quine will consist of two parts: a definition of a string and the program core. The string will contain the source code of the program core. And, what will the program core do? It will print the string twice: once to print the string definition, and again to print the program core.</p>
<p><span id="more-83"></span></p>
<p>That&#8217;s pretty much all we need to do, except for some details. When printing the string the first time, we need to escape special characters and surround each line with quotes. Also, some code may need to come before the string definition (the &#8220;header&#8221;), and some may need to come after the program core (the &#8220;footer&#8221;). Fortunately, we can stuff all the code we need into the program core, so handling these details is not a big problem.</p>
<p>Let&#8217;s walk through a quine construction in C#. The quine will look like this:</p>
<pre class="code"><span style="color: blue">    using </span>System;
<span style="color: blue"></span><span style="color: blue">    class </span><span style="color: #2b91af">P </span>{
        <span style="color: blue">static void </span>Main() {
            <span style="color: blue">string</span>[] S = {
                <span style="color: green">// the program core, as a string array
            </span>};

            <span style="color: green">// the program core, as source code:<span style="color: green">            //     1. Print the program header</span>
            //     2. Print S, formatted as the definition of S
            //     3. Print S, formatted as source code            //     4. Print the program footer</span><span style="color: green">
        </span>}
    }</pre>
<p>Let&#8217;s implement the program core. That&#8217;s easy:</p>
<p><a href="http://11011.net/software/vspaste"></a>
<pre class="code"><span style="color: blue">    using </span>System;
<span style="color: blue">    class </span><span style="color: #2b91af">P </span>{
        <span style="color: blue">static void </span>Main() {
            <span style="color: blue">string</span>[] S = {
                <span style="color: green">// <span style="color: green">the program core, represented as a string array </span></span>
            };
            <span style="color: green">// 1. Print the program header
            </span><span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"using System;"</span>);
            <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"class P {"</span>);
            <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"    static void Main() {"</span>);

            <span style="color: green">// 2. Print S, formatted as the definition of S
            </span><span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"        string[] S = {"</span>);
            <span style="color: blue">foreach </span>(<span style="color: blue">string </span>line <span style="color: blue">in </span>S)
            {
                <span style="color: blue">string </span>escapedLine = line.Replace(<span style="color: #a31515">@"\"</span>, <span style="color: #a31515">@"\\"</span>).Replace(<span style="color: #a31515">"\""</span>, <span style="color: #a31515">"\\\""</span>);
                <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"\"{0}\","</span>, escapedLine);
            }
            <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"        };"</span>);

            <span style="color: green">// 3. Print S, formatted as source code
            </span><span style="color: blue">foreach </span>(<span style="color: blue">string </span>line <span style="color: blue">in </span>S) <span style="color: #2b91af">Console</span>.WriteLine(line);

            <span style="color: green">// 4. Print the program footer
            </span><span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"    }"</span>);
            <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"}"</span>);
        }
    }</pre>
<p>We also need to initialize string S. To do that, simply copy &amp; paste the program core source code into the definition of S, add a backslash before each occurrence of &#8221; or \, and surround each line with quotes.</p>
<p>Here is the final quine:</p>
<pre class="code"><span style="color: blue">using </span>System;
<span style="color: blue">class </span><span style="color: #2b91af">P
</span>{
    <span style="color: blue">static void </span>Main()
    {
        <span style="color: blue">string</span>[] S = {
<span style="color: #a31515">"        Console.WriteLine(\"using System;\");"</span>,
<span style="color: #a31515">"        Console.WriteLine(\"class P {\");"</span>,
<span style="color: #a31515">"        Console.WriteLine(\"    static void Main() {\");"</span>,
<span style="color: #a31515">""</span>,
<span style="color: #a31515">"        Console.WriteLine(\"        string[] S = {\");"</span>,
<span style="color: #a31515">"        foreach (string line in S) {"</span>,
<span style="color: #a31515">"            string escapedLine = line.Replace(@\"\\\", @\"\\\\\")"</span>,
<span style="color: #a31515">"                .Replace(\"\\\"\", \"\\\\\\\"\");"</span>,
<span style="color: #a31515">"            Console.WriteLine(\"\\\"{0}\\\",\", escapedLine);"</span>,
<span style="color: #a31515">"        }"</span>,
<span style="color: #a31515">"        Console.WriteLine(\"        };\");"</span>,
<span style="color: #a31515">""</span>,
<span style="color: #a31515">"        foreach (string line in S) Console.WriteLine(line);"</span>,
<span style="color: #a31515">""</span>,
<span style="color: #a31515">"        Console.WriteLine(\"    }\");"</span>,
<span style="color: #a31515">"        Console.WriteLine(\"}\");"</span>,<span style="color: #a31515">
        </span>};
        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"using System;"</span>);
        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"class P {"</span>);
        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"    static void Main() {"</span>);

        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"        string[] S = {"</span>);
        <span style="color: blue">foreach </span>(<span style="color: blue">string </span>line <span style="color: blue">in </span>S)
        {
            <span style="color: blue">string </span>escapedLine = line.Replace(<span style="color: #a31515">@"\"</span>, <span style="color: #a31515">@"\\"</span>)
                .Replace(<span style="color: #a31515">"\""</span>, <span style="color: #a31515">"\\\""</span>);
            <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"\"{0}\","</span>, escapedLine);
        }
        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"        };"</span>);

        <span style="color: blue">foreach </span>(<span style="color: blue">string </span>line <span style="color: blue">in </span>S) <span style="color: #2b91af">Console</span>.WriteLine(line);

        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"    }"</span>);
        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"}"</span>);
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Pretty simple, isn&#8217;t it?</p>
<p>One interesting point is that if we add extra code into the program core, and add the same code into the definition of string S, we will still have a quine. For example, here is how you can extend to quine to print an arbitrary string to standard error, after printing its own source code to standard output:</p>
<pre class="code"><span style="color: blue">using </span>System;
<span style="color: blue">class </span><span style="color: #2b91af">P
</span>{
    <span style="color: blue">static void </span>Main()
    {
        <span style="color: blue">string</span>[] S = {
<span style="color: #a31515">"        Console.WriteLine(\"using System;\");"</span>,
<span style="color: #a31515">"        Console.WriteLine(\"class P {\");"</span>,
<span style="color: #a31515">"        Console.WriteLine(\"    static void Main() {\");"</span>,
<span style="color: #a31515">""</span>,
<span style="color: #a31515">"        Console.WriteLine(\"        string[] S = {\");"</span>,
<span style="color: #a31515">"        foreach (string line in S) {"</span>,
<span style="color: #a31515">"            string escapedLine = line.Replace(@\"\\\", @\"\\\\\")"</span>,
<span style="color: #a31515">"                .Replace(\"\\\"\", \"\\\\\\\"\");"</span>,
<span style="color: #a31515">"            Console.WriteLine(\"\\\"{0}\\\",\", escapedLine);"</span>,
<span style="color: #a31515">"        }"</span>,
<span style="color: #a31515">"        Console.WriteLine(\"        };\");"</span>,
<span style="color: #a31515">""</span>,
<span style="color: #a31515">"        foreach (string line in S) Console.WriteLine(line);"</span>,
<span style="color: #a31515">""</span>,
<span style="color: #a31515">"        Console.WriteLine(\"    }\");"</span>,
<span style="color: #a31515">"        Console.WriteLine(\"}\");"</span>,
<span style="color: #a31515">""</span>,
<span style="color: #a31515">"        Console.Error.WriteLine(\"This quine can do other things too!\");"</span>,
        };
        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"using System;"</span>);
        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"class P {"</span>);
        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"    static void Main() {"</span>);

        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"        string[] S = {"</span>);
        <span style="color: blue">foreach </span>(<span style="color: blue">string </span>line <span style="color: blue">in </span>S)
        {
            <span style="color: blue">string </span>escapedLine = line.Replace(<span style="color: #a31515">@"\"</span>, <span style="color: #a31515">@"\\"</span>)
                .Replace(<span style="color: #a31515">"\""</span>, <span style="color: #a31515">"\\\""</span>);
            <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"\"{0}\","</span>, escapedLine);
        }
        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"        };"</span>);

        <span style="color: blue">foreach </span>(<span style="color: blue">string </span>line <span style="color: blue">in </span>S) <span style="color: #2b91af">Console</span>.WriteLine(line);

        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"    }"</span>);
        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"}"</span>);

        <span style="color: #2b91af">Console</span>.Error.WriteLine(<span style="color: #a31515">"This quine can do other things too!"</span>);
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>So, we can write a program that knows how to print its source code, but also does other things. This is interesting for three reasons:</p>
<ol>
<li>It is an important result in theoretical computer science, known as the <a href="http://en.wikipedia.org/wiki/KRT">recursion theorem</a>. Recursion theorem can be used to prove a variety of interesting results. For example, using the recursion theorem is one way to prove that the halting problem is undecidable.
<li>Virus writers write programs that know how to replicate themselves, but also do other things, such as messing up your computer.
<li>You can write pointless but cool little programs, like my <a href="http://igoro.com/archive/self-printing-game-of-life-in-c">self-printing Game of Life</a>.</li>
</ol>
<p>By the way, the quine that I described in this article is by no means the shortest possible one in C#. Joey Wescott came up with <a href="http://yetanotherdeveloper.com/post/2008/01/20/My-Quine.aspx">a C# quine</a> that is only 166 characters long. I suggested two improvements, and we got it down to 149 characters (all one line):</p>
<pre class="code"><span style="color: blue">class </span><span style="color: #2b91af">P</span>{<span style="color: blue">static void </span>Main(){<span style="color: blue">var </span>S=<span style="color: #a31515">"class P{{static void Main(){{var S={1}{0}{1};System.Console</span></pre>
<pre class="code"><span style="color: #a31515"></span><span style="color: #a31515">.Write(S,S,'{1}');}}}}"</span>;System.<span style="color: #2b91af">Console</span>.Write(S,S,<span style="color: #a31515">'"'</span>);}}</pre>
<p>And there you have it - that&#8217;s how you write quines. In my next article, I will talk about an interesting little problem, and seven very different algorithms that can be used to solve it.</p>
<p><strong>Other articles you may like:</strong></p>
<p><a href="http://igoro.com/archive/numbers-that-cannot-be-computed/">Numbers that cannot be computed</a> </p>
<p><a href="http://igoro.com/archive/skip-lists-are-fascinating/">Skip list are fascinating!</a> </p>
<p><a href="http://igoro.com/archive/quicksort-killer/">Quicksort killer</a></p>
<img src="http://feeds.feedburner.com/~r/igoro/~4/2LBiXxWnNbE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://igoro.com/archive/how-to-write-a-self-printing-program/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Self-printing Game of Life in C#</title>
		<link>http://igoro.com/archive/self-printing-game-of-life-in-c/</link>
		<comments>http://igoro.com/archive/self-printing-game-of-life-in-c/#comments</comments>
		<pubDate>Thu, 30 Oct 2008 08:46:51 +0000</pubDate>
		<dc:creator>Igor Ostrovsky</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://igoro.com/archive/self-printing-game-of-life-in-c/</guid>
		<description><![CDATA[
Conway&#8217;s Game of Life has fascinated computer scientists for decades. Even though its rules are ridiculously simple, Conway&#8217;s universe gives rise to a variety of gliders, spaceships, oscillators, glider guns, and other forms of &#8220;life&#8221;. Self-printing programs are similarly curious, and - rather surprisingly - have an important place in the theory of computation.
What happens [...]]]></description>
			<content:encoded><![CDATA[</p>
<p>Conway&#8217;s Game of Life has fascinated computer scientists for decades. Even though its rules are ridiculously simple, Conway&#8217;s universe gives rise to a variety of gliders, spaceships, oscillators, glider guns, and other forms of &#8220;life&#8221;. Self-printing programs are similarly curious, and - rather surprisingly - have an important place in the theory of computation.</p>
<p>What happens when you combine the two? You are about to find out, but one thing is for sure: the geekiness factor should be pretty high.</p>
<p>I wrote a little C# program that contains a Game-of-Life grid. The program advances the game grid to the next generation and prints out a copy of itself, with the grid updated. You can take the output, compile it with a C# compiler, run it, and you&#8217;ll get the next generation of the game. You can iterate the process, or change the initial grid state manually.</p>
<p><span id="more-82"></span></p>
<p>Here is the source code:</p>
<div style="font-size: 8pt">
<pre class="code"><span style="color: blue">using </span>System;<span style="color: blue">class </span><span style="color: #2b91af">G  </span><span style="color: green">/* GAME OF LIFE by Igor Ostrovsky */  </span>{<span style="color: blue">static string</span>[]S={
<span style="color: #a31515">"############################################################################"</span>,
<span style="color: #a31515">"#                                                               * *        #"</span>,
<span style="color: #a31515">"#  ***                                                         *           #"</span>,
<span style="color: #a31515">"#                                       *                      *           #"</span>,
<span style="color: #a31515">"#                                     * *                      *  *        #"</span>,
<span style="color: #a31515">"#                           **      **            **           ***         #"</span>,
<span style="color: #a31515">"#                          *   *    **            **                       #"</span>,
<span style="color: #a31515">"#               **        *     *   **                                     #"</span>,
<span style="color: #a31515">"#               **        *   * **    * *                                  #"</span>,
<span style="color: #a31515">"#                         *     *       *                                  #"</span>,
<span style="color: #a31515">"#                          *   *                                           #"</span>,
<span style="color: #a31515">"#                           **                                             #"</span>,
<span style="color: #a31515">"#   **     **                                                              #"</span>,
<span style="color: #a31515">"#    **   **                                        *  *                   #"</span>,
<span style="color: #a31515">"# *  * * * *  *                                         *                  #"</span>,
<span style="color: #a31515">"# *** ** ** ***                                     *   *                  #"</span>,
<span style="color: #a31515">"#  * * * * * *                                       ****                  #"</span>,
<span style="color: #a31515">"#   ***   ***                                                              #"</span>,
<span style="color: #a31515">"#                                                                          #"</span>,
<span style="color: #a31515">"#   ***   ***                                                              #"</span>,
<span style="color: #a31515">"#  * * * * * *            *                                                #"</span>,
<span style="color: #a31515">"# *** ** ** ***           *           *  *                             *** #"</span>,
<span style="color: #a31515">"# *  * * * *  *                           *                           *  * #"</span>,
<span style="color: #a31515">"#    **   **             ***          *   *                **            * #"</span>,
<span style="color: #a31515">"#   **     **                          ****                              * #"</span>,
<span style="color: #a31515">"#                                                                     * *  #"</span>,
<span style="color: #a31515">"############################################################################"</span>,
};<span style="color: blue">static void </span>Main(){<span style="color: blue">string </span>T=<span style="color: #a31515">"\",r=\"using System;class G  /* GAME OF LIFE b"</span>+
<span style="color: #a31515">"y Igor Ostrovsky \"+\"*/  {static string[]S={\\n\";int p=31,i,j,b,d;for(i=0;"</span>+
<span style="color: #a31515">"i&lt;27;i++){r+='\"'; for(j=0;j&lt;76;j++){if(S[i][j]!='#'){b=0;for(d=0;d&lt;9;d++)if"</span>+
<span style="color: #a31515">"(S[i-1+d/3][j-1+d%3]=='*')b++;r+=b==3 ||(S[i][j]=='*'&amp;&amp;b==4)?'*':' ';} else "</span>+
<span style="color: #a31515">"r+='#';}r+=\"\\\",\\n\";}r+=\"};static\"+\" void Main(){string T=\\\"\";fore"</span>+
<span style="color: #a31515">"ach(var c in T){if(c=='\\\\'||c=='\"'){r+='\\\\';p++;} r+=c; if(++p&gt;=77){r+="</span>+
<span style="color: #a31515">"\"\\\"+\\n\\\"\";p=1;}} foreach(var c in T){r+=c;if(++p%79==0)r+='\\n';}Cons"</span>+
<span style="color: #a31515">"ole.Write(r);}}"</span>,r=<span style="color: #a31515">"using System;class G  /* GAME OF LIFE by Igor Ostrovsky "</span>+
<span style="color: #a31515">"*/  {static string[]S={\n"</span>;<span style="color: blue">int </span>p=31,i,j,b,d;<span style="color: blue">for</span>(i=0;i&lt;27;i++){r+=<span style="color: #a31515">'"'</span>; <span style="color: blue">for</span>(j=0;
j&lt;76;j++){<span style="color: blue">if</span>(S[i][j]!=<span style="color: #a31515">'#'</span>){b=0;<span style="color: blue">for</span>(d=0;d&lt;9;d++)<span style="color: blue">if</span>(S[i-1+d/3][j-1+d%3]==<span style="color: #a31515">'*'</span>)b++;
r+=b==3 ||(S[i][j]==<span style="color: #a31515">'*'</span>&amp;&amp;b==4)?<span style="color: #a31515">'*'</span>:<span style="color: #a31515">' '</span>;} <span style="color: blue">else </span>r+=<span style="color: #a31515">'#'</span>;}r+=<span style="color: #a31515">"\",\n"</span>;}r+=<span style="color: #a31515">"};static"
</span>+<span style="color: #a31515">" void Main(){string T=\""</span>;<span style="color: blue">foreach</span>(<span style="color: blue">var </span>c <span style="color: blue">in </span>T){<span style="color: blue">if</span>(c==<span style="color: #a31515">'\\'</span>||c==<span style="color: #a31515">'"'</span>){r+=<span style="color: #a31515">'\\'</span>;p++
;} r+=c; <span style="color: blue">if</span>(++p&gt;=77){r+=<span style="color: #a31515">"\"+\n\""</span>;p=1;}} <span style="color: blue">foreach</span>(<span style="color: blue">var </span>c <span style="color: blue">in </span>T){r+=c;<span style="color: blue">if</span>(++p%79==0)
r+=<span style="color: #a31515">'\n'</span>;}<span style="color: #2b91af">Console</span>.Write(r);}}</pre>
</div>
<p><font color="#0000ff"></font>&nbsp;</p>
<p>And is here the output the program prints. The output is the same as the source code, except that the game has advanced to the next generation:</p>
<div style="font-size: 8pt">
<pre>using System;class G  /* GAME OF LIFE by Igor Ostrovsky */  {static string[]S={
"############################################################################",
"#   *                                                                      #",
"#   *                                                          **          #",
"#   *                                  *                      ***          #",
"#                                    * *                      ** *         #",
"#                           *       * *           **           ***         #",
"#                          **      *  *           **            *          #",
"#               **        **    **  * *                                    #",
"#               **       ***    **   * *                                   #",
"#                         **    **     *                                   #",
"#                          **                                              #",
"#                           *                                              #",
"#   ***   ***                                                              #",
"#                                                                          #",
"# *    * *    *                                        **                  #",
"# *    * *    *                                      ** **                 #",
"# *    * *    *                                      ****                  #",
"#   ***   ***                                         **                   #",
"#                                                                          #",
"#   ***   ***                                                              #",
"# *    * *    *                                                         *  #",
"# *    * *    *                                                        *** #",
"# *    * *    *          * *             **                            * **#",
"#                         *            ** **                            ***#",
"#   ***   ***             *            ****                             ** #",
"#                                       **                                 #",
"############################################################################",
};static void Main(){string T="\",r=\"using System;class G  /* GAME OF LIFE b"+
"y Igor Ostrovsky \"+\"*/  {static string[]S={\\n\";int p=31,i,j,b,d;for(i=0;"+
"i&lt;27;i++){r+='\"'; for(j=0;j&lt;76;j++){if(S[i][j]!='#'){b=0;for(d=0;d&lt;9;d++)if"+
"(S[i-1+d/3][j-1+d%3]=='*')b++;r+=b==3 ||(S[i][j]=='*'&amp;&amp;b==4)?'*':' ';} else "+
"r+='#';}r+=\"\\\",\\n\";}r+=\"};static\"+\" void Main(){string T=\\\"\";fore"+
"ach(var c in T){if(c=='\\\\'||c=='\"'){r+='\\\\';p++;} r+=c; if(++p&gt;=77){r+="+
"\"\\\"+\\n\\\"\";p=1;}} foreach(var c in T){r+=c;if(++p%79==0)r+='\\n';}Cons"+
"ole.Write(r);}}",r="using System;class G  /* GAME OF LIFE by Igor Ostrovsky "+
"*/  {static string[]S={\n";int p=31,i,j,b,d;for(i=0;i&lt;27;i++){r+='"'; for(j=0;
j&lt;76;j++){if(S[i][j]!='#'){b=0;for(d=0;d&lt;9;d++)if(S[i-1+d/3][j-1+d%3]=='*')b++;
r+=b==3 ||(S[i][j]=='*'&amp;&amp;b==4)?'*':' ';} else r+='#';}r+="\",\n";}r+="};static"
+" void Main(){string T=\"";foreach(var c in T){if(c=='\\'||c=='"'){r+='\\';p++
;} r+=c; if(++p&gt;=77){r+="\"+\n\"";p=1;}} foreach(var c in T){r+=c;if(++p%79==0)
r+='\n';}Console.Write(r);}}
</pre>
</div>
<p>&nbsp;</p>
<p>If you want to see the program iterate, save the source code into a file named life.cs, and run this command repeatedly from a Visual Studio console:</p>
<pre class="code">csc.exe life.cs &amp;&amp; (life &gt; life.cs) &amp;&amp; life</pre>
<p>Cool, isn&#8217;t it? I have a follow-up article nearly ready that explains how to write programs like this one&#8230; just in case you ever wanted to. <img src='http://igoro.com/wordpress/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>[Update] The follow-up <a href="http://igoro.com/archive/how-to-write-a-self-printing-program/">How to write a self-printing program</a> is up.</p>
<p><strong>More articles:</strong></p>
<p><a title="Permanent Link- Numbers that cannot be computed" href="http://igoro.com/archive/numbers-that-cannot-be-computed/">Numbers that cannot be computed</a></p>
<p><a href="http://igoro.com/archive/skip-lists-are-fascinating/">Skip list are fascinating!</a></p>
<p><a href="http://igoro.com/archive/quicksort-killer/">Quicksort killer</a></p>
<img src="http://feeds.feedburner.com/~r/igoro/~4/6w72oYbLAYE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://igoro.com/archive/self-printing-game-of-life-in-c/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
