<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Stefano Ricciardi &#187; .NET</title>
	<atom:link href="http://stefanoricciardi.com/category/net/feed/" rel="self" type="application/rss+xml" />
	<link>http://stefanoricciardi.com</link>
	<description>On Software Development and Thereabouts</description>
	<lastBuildDate>Tue, 15 Nov 2011 07:57:34 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Dependency Injection for Dummies</title>
		<link>http://stefanoricciardi.com/2011/11/08/dependency-injection-for-dummies/</link>
		<comments>http://stefanoricciardi.com/2011/11/08/dependency-injection-for-dummies/#comments</comments>
		<pubDate>Tue, 08 Nov 2011 09:10:31 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Design and Patterns]]></category>
		<category><![CDATA[agile]]></category>
		<category><![CDATA[IoC]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1487</guid>
		<description><![CDATA[Antonio Vidal has translated this post into Spanish: you can find it here. Dependency injection is a very simple concept: if you have an object that interacts with other objects the responsibility of finding a reference to those objects at run time is moved outside of the object itself. What does it mean for an [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2011%2F11%2F08%2Fdependency-injection-for-dummies%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2011%2F11%2F08%2Fdependency-injection-for-dummies%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p><em><a href="http://codecriticon.com/">Antonio Vidal</a> has translated this post into Spanish: you can find it <a href="http://codecriticon.com/dependencia-inyeccion-dummies/">here</a>.</em></p>
<p>Dependency injection is a very simple concept: if you have an object that interacts with other objects the responsibility of finding a reference to those objects at run time is moved outside of the object itself.</p>
<p>What does it mean for an object to &quot;interact&quot; with other objects? Generally it means invoking methods or reading properties from those objects. So if we have a class <code>A</code> that invokes method <code>Calculate</code> on class <code>B</code>, we can say that <code>A</code> interacts with <code>B</code>.</p>
<p>In the following example we show class <code>A</code> interacting with class <code>B</code>. We can equally say that <class>A</class> <i>depends</i> on class <code>B</code> to fulfill a responsibility. In this case, it not only invokes its method <code>Calculate</code> but it also creates a new instance of that class.</p>
<pre class="brush:csharp">class A
{
  private B _b;

  public A
  {
    _b = new B();
  }

  public int SomeMethod()
  {
    return (_b.Calculate() * 2);
  }
}</pre>
<p>In the following example, on the other side, the responsibility of getting a reference to an implementation of a class of type <code>B</code> is moved <i>outside</i> of <code>A</code>:</p>
<pre class="brush:csharp">class A
{
  private B _b;
  public A(B b)
  {
    _b = b;
  }
  public int SomeMethod()
  {
    return _(b.Calculate * 2);
  }
}</pre>
<p>In this case we say that a dependency (<code>B</code>) has been <i>injected</i> into <code>A</code>, via the constructor. Of course, you can also inject dependencies via a property (or even a regular method), like in the following example:</p>
<pre class="brush:csharp">class A
{
  private B _b;

  public B B
  {
     get { return _b; }
     set { _b = value; }
  }

  public int SomeMethod()
  {
    if (_b != null)
        return _b.RetrieveValue() * 2;}
    else
        // HANDLE THIS ERROR CASE
        return -1;
  }
}</pre>
<p>So this is all there is about dependency injection. Everything else just builds on this core concept.</p>
<p>Like for example Inversion Of Control (IoC) tools which helps you wiring together your objects at run time, injecting all dependencies as needed. So what exactly is Inversion of Control and how does it relate to Dependency Injection (DI)?</p>
<p>I like to associate IoC to the <a href="http://en.wikipedia.org/wiki/Hollywood_Principle">Hollywood Principle</a>: &quot;<em>Don&#39;t call us, we&#39;ll call you</em>&quot;. IoC is a design principle where <quote>reusable generic code controls the execution of problem-specific code</quote>: it is a characteristic of many frameworks, where the application is built extending or customizing a common skeleton; you put your own classes at specific points and the framework will call you when needed.</p>
<p>You can use an IoC container as a framework to perform Dependency Injection on your behalf: you tell the container which are the concrete implementation classes for your dependencies and the container will make sure that your constructors or setters will be called with the right objects.</p>
<p>Therefore, IoC containers are just a <i>convenience</i> to simplify how dependency injection is handled. But even if you don&#39;t use one you could still manually perform dependency injection.</p>
<p>(If you want to have a look at how an IoC container works you can jump to my <a href="http://stefanoricciardi.com/2011/01/21/ninject-mini-tutorial-part-1/">mini tutorial on Ninject</a>).</p>
<p>Why is the concept of dependency injection important? Because by applying it, you simplify your design (separating the responsibility of using an object from the responsibility of retrieving that object) and your code becomes much easier to test, since you can mock out the dependencies substituting them with fake (stub) objects. But that is the subject for another post.</p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2011/11/08/dependency-injection-for-dummies/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Why Functional Programming Matters in Fsharp</title>
		<link>http://stefanoricciardi.com/2011/07/16/whyfunctionalprogrammingmattersinfsharp/</link>
		<comments>http://stefanoricciardi.com/2011/07/16/whyfunctionalprogrammingmattersinfsharp/#comments</comments>
		<pubDate>Sat, 16 Jul 2011 17:46:12 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[F#]]></category>
		<category><![CDATA[functional]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/2011/07/16/building-reduce-and-map-functions-from-the-ground-up-in-fsharp/</guid>
		<description><![CDATA[Today I&#39;ve found myself reading again the excellent paper Why Functional Programming Matters, where the author describes the core activity of programming in a functional fashion in terms of &#34;glueing functions together&#34;. It&#39;s been a while since I last played around with F#. So I decided this would be a good time to refresh some [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2011%2F07%2F16%2Fwhyfunctionalprogrammingmattersinfsharp%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2011%2F07%2F16%2Fwhyfunctionalprogrammingmattersinfsharp%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
</p>
<p>Today I&#39;ve found myself reading again the excellent paper <a href="http://stefanoricciardi.com/blog/wp-content/uploads/2011/07/WhyFunctionalProgrammingMatters.pdf">Why Functional Programming Matters</a>, where the author describes the core activity of programming in a functional fashion in terms of &quot;glueing functions together&quot;.</p>
<p>It&#39;s been a while since I last played around with F#. So I decided this would be a good time to refresh some of the core concepts by translating some of the examples from his paper into F#.</p>
<h2>Reduce</h2>
<p>The paper starts off describing how a <code>reduce</code> function could be devised, extrapolating a common behavior from a certain set of functions. Let&#39;s first consider a function to sum all the items in a list:</p>
<pre class="brush:fsharp">    let add a b = a + b

    let rec sum l =
        match l with
        | [] -&gt; 0
        | h::t -&gt; add h (sum t)
  </pre>
<p>Nothing too fancy going on here. Let&#39;s now consider a similar function that instead multiplies together all the items in a list:</p>
<pre class="brush:fsharp">    let mul a b = a * b

    let rec product l =
        match l with
        | [] -&gt; 1
        | h::t -&gt; mul h (product t)
  </pre>
<p>If you compare the structure of the two functions <code>sum</code> and <code>product</code> you can see that the two are very similar. The are only two differences between the two:</p>
<ul>
<li>The value being returned when an empty list is matched (0 vs 1).</li>
<li>The function being applied between the head of the list and the application of the recursive function to the remaining of the list (<code>add</code> vs <code>mul</code>)</li>
</ul>
<p>It&#39;s easy, then, to extrapolate a more general <code>reduce</code> function, as follows:</p>
<pre class="brush:fsharp">    let rec reduce f a l =
        match l with
        | [] -&gt; a
        | h::t -&gt; f h ((reduce f a) t)
  </pre>
<p>Let&#39;s consider all the pieces step by step:</p>
<ul>
<li><code>reduce</code> is a (recursive) function accepting a function <code>f</code>, a value <code>a</code> and a list <code>l</code>.</li>
<li><code>f</code> is the function that we want to apply between two elements of the list (<code>sum</code> or <code>mul</code> in the two examples above)</li>
<li><code>a</code> is the value that we want to return when <code>f</code> is applied to the empty list (0 or 1 respectively), and</li>
<li><code>l</code> is the actual list we want to operate on.</li>
</ul>
<p>Let&#39;s try this new function in the interactive window:</p>
<pre class="brush:fsharp">  &gt; reduce;;
  val it : ((&#39;a -&gt; &#39;b -&gt; &#39;b) -&gt; &#39;b -&gt; &#39;a list -&gt; &#39;b)
  &gt; reduce add 0 [1;2;3];;
  val it : int = 6
  &gt; reduce mul 1 [1;2;3];;
  val it : int = 6
  </pre>
<p>As you see, the compiler infers the types involved in <code>reduce</code> as follows:</p>
<ul>
<li><code>(&#39;a -&gt; &#39;b -&gt; b&#39;)</code> is the description of f: a function that takes two arguments of type &#39;a and &#39;b and returns one item of type &#39;b (note that &#39;a and &#39;b may in some cases represent the same type, as with <code>add</code> and <code>mul</code>).</li>
<li><code>&#39;b</code> is a parameter of the same type as the one returned by <code>f</code>.</li>
<li><code>&#39;a list</code>is a list of items the same type as the first argument of <code>f</code>.</li>
<li><code>&#39;b</code> is finally the return type of the whole reduction process</li>
<p>	.</ul>
<p>There&#39;s an interesting special case: when <code>&#39;b</code> is <code>&#39;a list</code>. That is, when <code>f</code> has the following form: (&#39;a -&gt; a&#39; list -&gt; a&#39; list). A function receiving an item and a list and returning another list. Can you think of any function like that? What about concatenating an item and a list?</p>
<pre class="brush:fsharp">    let cons a l = a::l
  </pre>
<p>Let&#39;s see how the F# interactive interprets the new function we&#39;ve just created and an example of usage:</p>
<pre class="brush:fsharp">    &gt; cons;;
    val it : (&#39;a -&gt; &#39;a list -&gt; &#39;a list)
    &gt; cons 1 [2; 3];;
    val it : int list = [1; 2; 3]
    &gt;
  </pre>
<p>And we now consider <code>cons</code> as our <code>f</code> function, first parameter of the <code>reduce</code>, we can write for example:</p>
<pre class="brush:fsharp">    let append a b = reduce cons b a
    let copy l = reduce cons l []
  </pre>
<p>where <code>append</code> concatenates two lists and <code>copy</code> simply replicates any given list:</p>
<pre class="brush:fsharp">    &gt; append;;
    val it : (&#39;a list -&gt; &#39;a list -&gt; &#39;a list)
    &gt; append [1;2] [3;4];;
    val it : int list = [1; 2; 3; 4]
    &gt;  copy;;
    val it : (&#39;a list -&gt; &#39;a list)
    &gt; copy [1;2;3];;
    val it : int list = [1; 2; 3]
    &gt;
</pre>
<p>In the following post we&#39;ll continue translating some more core functions from the &quot;Why Functional Programming Matters&quot; into F#. Stay tuned!</p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2011/07/16/whyfunctionalprogrammingmattersinfsharp/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Code Snippets for the Dispose Pattern</title>
		<link>http://stefanoricciardi.com/2011/05/25/code-snippets-for-the-dispose-pattern/</link>
		<comments>http://stefanoricciardi.com/2011/05/25/code-snippets-for-the-dispose-pattern/#comments</comments>
		<pubDate>Wed, 25 May 2011 14:08:34 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[snippet]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[visual studio 2010]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1407</guid>
		<description><![CDATA[         ]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2011%2F05%2F25%2Fcode-snippets-for-the-dispose-pattern%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2011%2F05%2F25%2Fcode-snippets-for-the-dispose-pattern%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>I thougth I&#8217;d just share a couple of Visual Studio C# code snippets to implement disposable classes, based on the well known .NET <a href="http://msdn.microsoft.com/en-us/library/b1yfkh5e(v=VS.100).aspx">dispose pattern</a>.</p>
<p>You can download it from <a href="http://stefanoricciardi.com/blog/wp-content/uploads/2011/05/DisposePattern.zip">here</a> or simply copy and past it from the listing below. Feel free to rename the shortcut to whatever you like <img src='http://stefanoricciardi.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<pre class="brush:xml">
&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"&gt;
  &lt;CodeSnippet Format="1.0.0"&gt;
    &lt;Header&gt;
      &lt;Title&gt;Base class disposable implementation.&lt;/Title&gt;
      &lt;Shortcut&gt;bdisp&lt;/Shortcut&gt;
      &lt;Description&gt;
        Code snippet to create a scheleton implementation
        of the IDisposable pattern for a base class.
      &lt;/Description&gt;
      &lt;Author&gt;Stefano Ricciardi&lt;/Author&gt;
      &lt;SnippetTypes&gt;
        &lt;SnippetType&gt;Expansion&lt;/SnippetType&gt;
      &lt;/SnippetTypes&gt;
    &lt;/Header&gt;
    &lt;Snippet&gt;
      &lt;Declarations&gt;
        &lt;Literal&gt;
          &lt;ID&gt;ClassName&lt;/ID&gt;
          &lt;ToolTip&gt;Name of the class.&lt;/ToolTip&gt;
          &lt;Default&gt;ClassName&lt;/Default&gt;
        &lt;/Literal&gt;
      &lt;/Declarations&gt;
      &lt;Code Language="csharp"&gt;
        &lt;![CDATA[
    public class $ClassName$: IDisposable
    {
        private bool _disposed = false;

        //Implement IDisposable.
        public void Dispose()
        {
          Dispose(true);
          GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
          if (!_disposed)
          {
            if (disposing)
            {
              // Free other state (managed objects).
            }
            // Free your own state (unmanaged objects).
            // Set large fields to null.
            _disposed = true;
          }
        }

        // Use C# destructor syntax for finalization code.
        ~$ClassName$()
        {
          // Simply call Dispose(false).
          Dispose(false);
        }
    }            ]]&gt;
      &lt;/Code&gt;
    &lt;/Snippet&gt;
  &lt;/CodeSnippet&gt;
  &lt;CodeSnippet Format="1.0.0"&gt;
    &lt;Header&gt;
      &lt;Title&gt;Base class disposable implementation.&lt;/Title&gt;
      &lt;Shortcut&gt;ddisp&lt;/Shortcut&gt;
      &lt;Description&gt;
        Code snippet to create a scheleton implementation of the
        IDisposable pattern	for a derived class.
      &lt;/Description&gt;
      &lt;Author&gt;Stefano Ricciardi&lt;/Author&gt;
      &lt;SnippetTypes&gt;
        &lt;SnippetType&gt;Expansion&lt;/SnippetType&gt;
      &lt;/SnippetTypes&gt;
    &lt;/Header&gt;
    &lt;Snippet&gt;
      &lt;Declarations&gt;
        &lt;Literal&gt;
          &lt;ID&gt;DerivedClassName&lt;/ID&gt;
          &lt;ToolTip&gt;Name of the derived class.&lt;/ToolTip&gt;
          &lt;Default&gt;Derived&lt;/Default&gt;
        &lt;/Literal&gt;
        &lt;Literal&gt;
          &lt;ID&gt;BaseClassName&lt;/ID&gt;
          &lt;ToolTip&gt;Name of the base class.&lt;/ToolTip&gt;
          &lt;Default&gt;Base&lt;/Default&gt;
        &lt;/Literal&gt;
      &lt;/Declarations&gt;
      &lt;Code Language="csharp"&gt;
        &lt;![CDATA[
  public class $DerivedClassName$: $BaseClassName$
  {
      private bool _disposed = false;

      protected override void Dispose(bool disposing)
      {
          if (!_disposed)
          {
              if (disposing)
              {
                  // Release managed resources.
              }
              // Release unmanaged resources.
              // Set large fields to null.
              // Call Dispose on your base class.

              _disposed = true;
          }

          base.Dispose(disposing);
      }
      // The derived class does not have a Finalize method
      // or a Dispose method without parameters because it inherits
      // them from the base class.
  }
]]&gt;
      &lt;/Code&gt;
    &lt;/Snippet&gt;
  &lt;/CodeSnippet&gt;
&lt;/CodeSnippets&gt;
</pre>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2011/05/25/code-snippets-for-the-dispose-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ninject Mini Tutorial &#8211; Part 2</title>
		<link>http://stefanoricciardi.com/2011/02/04/ninject-mini-tutorial-part-2/</link>
		<comments>http://stefanoricciardi.com/2011/02/04/ninject-mini-tutorial-part-2/#comments</comments>
		<pubDate>Fri, 04 Feb 2011 13:17:43 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Design and Patterns]]></category>
		<category><![CDATA[IoC]]></category>
		<category><![CDATA[ninject]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1337</guid>
		<description><![CDATA[Go to Part 1 &#160; Controlling the Life Cycle of your Objects In the previous post we did not concern ourselves with the lifecycle of the object returned from Ninject kernel. Ninject provides the following 4 built-in lifecycles (scopes): Transient (default) Singleton (only one instance) Thread (one instance per thread) Request (one instance per web [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2011%2F02%2F04%2Fninject-mini-tutorial-part-2%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2011%2F02%2F04%2Fninject-mini-tutorial-part-2%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p><em>Go to <a href="http://stefanoricciardi.com/2011/01/21/ninject-mini-tutorial-part-1/">Part 1</a></em></p>
<p>&nbsp;</p>
<h2>Controlling the Life Cycle of your Objects</h2>
<p>In the previous post we did not concern ourselves with the lifecycle of the object returned from Ninject kernel. Ninject provides the following 4 built-in lifecycles (<em>scopes</em>):</p>
<ol>
<li>Transient (default)</li>
<li>Singleton (only one instance)</li>
<li>Thread (one instance per thread)</li>
<li>Request (one instance per web request).</li>
</ol>
<p>You can create <em>custom scopes</em> if needed.</p>
<h4>Singleton:</h4>
<pre class="brush:csharp">using (IKernel kernel = new StandardKernel())
{
    kernel.Bind&lt;ITaxCalculator&gt;()
        .To&lt;TaxCalculator&gt;()
        .InSingletonScope()
        .WithConstructorArgument(&quot;rate&quot;, .2M);

    var tc1 = kernel.Get&lt;ITaxCalculator&gt;();
    var tc2 = kernel.Get&lt;ITaxCalculator&gt;();

    Assert.Same(tc1, tc2);
}</pre>
<h4>Transient:</h4>
<pre class="brush:csharp">using (IKernel kernel = new StandardKernel())
{
    kernel.Bind&lt;ITaxCalculator&gt;()
        .To&lt;TaxCalculator&gt;()
        .InTransientScope()
        .WithConstructorArgument(&quot;rate&quot;, .2M);

        var tc1 = kernel.Get&lt;ITaxCalculator&gt;();
        var tc2 = kernel.Get&lt;ITaxCalculator&gt;();

        Assert.NotSame(tc1, tc2);
}</pre>
<h2>More Details on Injection Patterns</h2>
<p>With Ninject you can inject:</p>
<ol>
<li>Constructor parameters</li>
<li>Properties</li>
<li>Methods</li>
</ol>
<p>Before considering each one in turn, we just need to introduce the <code>[Inject]</code> attribute which may be used to tag constructors, properties and methods requiring injection. Obviously, by tagging constructors, properties or methods, your objects cease to be <a href="http://en.wikipedia.org/wiki/Plain_Old_CLR_Object">POCO</a>s.</p>
<h3>Constructor Injection</h3>
<p>We have already seen an example of constructor injection in <a href="http://stefanoricciardi.com/2011/01/21/ninject-mini-tutorial-part-1/">Part I</a> when the kernel auto-magically injected an implementation of <code>ITaxCalculator</code> to the <code>Sale Area</code> constructor. In that case, even if we didn&#39;t tag the constructor with the <code>[Inject]</code> attribute, the kernel was able to perform the required binding. How?</p>
<p>That was actually a special case: when there is <em>only one</em> constructor available, the tagging is not needed. On the other hand, if there&#39;s more than one constructor defined, then then kernel can inject a dependency to only one constructor that needs to have the <code>[Inject]</code> attribute:</p>
<pre class="brush:fsharp">public class Sale3
{
    private readonly ITaxCalculator taxCalculator;

    public Sale3() { }

    [Inject]
    public Sale3(ITaxCalculator taxCalculator)
    {
        this.taxCalculator = taxCalculator;
    }

    // other stuff
}</pre>
<h3>Properties Injection</h3>
<p>Instead of passing in the dependencies through the constructor, you can also inject them as properties. Injecting properties is pretty straightforward:</p>
<pre class="brush:csharp">public class Sale2
{
    [Inject]
    public ITaxCalculator TaxCalculator { get; set; } 

    // implicit default constructor and other stuff... 

    public decimal GetTotal()
    {
        decimal total = 0M;
        foreach (var item in lineItems)
        {
            total += TaxCalculator.CalculateTax(item.TotalPrice)
                    + item.TotalPrice;
        } 

        return total;
    }
}</pre>
<p>Usage (note that we never explicitely set the <code>TaxCalculator</code>):</p>
<pre class="brush:csharp">using (IKernel kernel = new StandardKernel())
{
    kernel.Bind&lt;ITaxCalculator&gt;()
                  .To&lt;TaxcCalculator&gt;()
                  .WithConstructorArgument(&quot;rate&quot;, .2M);

    var lineItem1 = new SaleLineItem(&quot;Gone with the wind&quot;, 10M, 1);
    var lineItem2 = new SaleLineItem(&quot;Casablanca&quot;, 5M, 2);

    var sale = kernel.Get&lt;Sale2&gt;(); // property injection!
    sale.AddItem(lineItem1);
    sale.AddItem(lineItem2);

    Assert.Equal(24M, sale.GetTotal());
}</pre>
<p>There&#39;s an important caveat: if you have 2 or more properties injected, the order in which each dependency is injected is not predictable. This might complicate your design, if those dependencies are coupled somehow (e.g. dependency A needs dependency B). For this kind of situations, constructor or method injection is usually preferred.</p>
<h3>Methods Injection</h3>
<p>Finally, it&rsquo;s also possible to tag methods for injection. As with constructor parameters, it&rsquo;s possible to inject more than one value at once.</p>
<pre class="brush:csharp">public class Sale4
{
    private ITaxCalculator taxCalculator;

    // other stuff

    // method injection, will be called by the kernel
    [Inject]
    public void SetTaxCalculator(ITaxCalculator taxCalculator)
    {
        this.taxCalculator = taxCalculator;
    }

    public decimal GetTotal()
    {
        decimal total = 0M;
        foreach (var item in lineItems)
        {
            total += taxCalculator.CalculateTax(item.TotalPrice)
                  + item.TotalPrice;
        }

        return total;
    }
}</pre>
<p>Usage (note that we never explicitely call the <code>SetTaxCalculator</code>):</p>
<pre class="brush:csharp">using (IKernel kernel = new StandardKernel())
{
    kernel.Bind&lt;ITaxCalculator&gt;()
          .To&lt;TaxCalculator&gt;()
          .WithConstructorArgument(&quot;rate&quot;, .2M);

    var lineItem1 = new SaleLineItem(&quot;Gone with the wind&quot;, 10M, 1);
    var lineItem2 = new SaleLineItem(&quot;Casablanca&quot;, 5M, 2);

    var sale = kernel.Get&lt;Sale4&gt;(); // method injection!
    sale.AddItem(lineItem1);
    sale.AddItem(lineItem2);

    Assert.Equal(24M, sale.GetTotal());
}</pre>
<p><em>Go to <a href="http://stefanoricciardi.com/2011/01/21/ninject-mini-tutorial-part-1/">Part 1</a></em></p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2011/02/04/ninject-mini-tutorial-part-2/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2011/02/04/ninject-mini-tutorial-part-2/" border="0" alt="kick it on DotNetKicks.com" /></a></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2011/02/04/ninject-mini-tutorial-part-2/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Ninject Mini Tutorial &#8211; Part 1</title>
		<link>http://stefanoricciardi.com/2011/01/21/ninject-mini-tutorial-part-1/</link>
		<comments>http://stefanoricciardi.com/2011/01/21/ninject-mini-tutorial-part-1/#comments</comments>
		<pubDate>Fri, 21 Jan 2011 13:12:23 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Design and Patterns]]></category>
		<category><![CDATA[IoC]]></category>
		<category><![CDATA[ninject]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1327</guid>
		<description><![CDATA[What Is Ninject There are several Inversion of Control (IoC) containers for .NET to pick from (such as Castle Windsor, Structure Map and Microsoft Unity, just to name just a few).&#160; Ninject is one of the newest entries in the arena, but it&#8217;s now sufficiently stable at version 2.0. Ninject tries to focus on &#8220;simplicity [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2011%2F01%2F21%2Fninject-mini-tutorial-part-1%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2011%2F01%2F21%2Fninject-mini-tutorial-part-1%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<h2>What Is Ninject</h2>
<p>There are several Inversion of Control (IoC) containers for .NET to pick from (such as <a href="http://stw.castleproject.org/Windsor.MainPage.ashx">Castle Windsor</a>, <a href="http://structuremap.net/structuremap/index.html">Structure Map</a> and <a href="http://msdn.microsoft.com/en-us/library/ff663144.aspx">Microsoft Unity</a>, just to name just a few).&nbsp; <a href="http://ninject.org/">Ninject</a> is one of the newest entries in the arena, but it&rsquo;s now sufficiently stable at version 2.0.</p>
<p>Ninject tries to focus on &ldquo;<em>simplicity and ease of use</em>&rdquo;, removing features that are not deemed necessary (to the point that XML configuration is not offered out-of-the box).</p>
<p>In this and following posts we&rsquo;ll explore some example of how to use Ninject. I assume that you are somehow familiar with the basic concepts of <em>Inversion of Control</em> and <em>Dependency Injection</em>; if that&rsquo;s not the case, you should consider having a look at this <a href="http://en.wikipedia.org/wiki/Inversion_of_control">wikipedia entry</a> (better yet, take some time and read Martin Fowler f<a href="http://martinfowler.com/articles/injection.html">amous post</a> on the subject).&nbsp;&nbsp;</p>
<h2>Setup</h2>
<p>Installing Ninject is quite easy: you simply download the pre-built DLLs it from <a href="http://ninject.org/download">here</a>. Since Ninject is open source, you can also get the sources from <a href="https://github.com/ninject/ninject">github</a> and build it on your own.</p>
<p>On my Windows machine, I have copied the DLLs on <em>C:\Ninject</em>.</p>
<h2>Getting your Feet Wet With Ninject</h2>
<p>Once you have Ninject DLLs somewhere on your hard-drive, in order to get started you only need to reference them (typically you only need to reference <tt>NInject.dll</tt> ). As we said, no XML configuration is required.</p>
<p>Let&rsquo;s see a few basic examples (the complete source code with unit tests I present in this series are available on <a href="https://github.com/stefanoric/NINJECTTUTORIAL">github</a>).</p>
<h3>&quot;Hello, Ninject&rdquo;</h3>
<p>Suppose we have a fairly simple service to calculate the taxes for a given amount, defined in an <code>ITaxCalculator</code> interface:</p>
<pre class="brush:csharp">decimal CalculateTax(decimal gross);</pre>
<p>and a trivial implementation <code>TaxCalculator</code> as follows:</p>
<pre class="brush:csharp">public class TaxCalculator : ITaxCalculator
{
    private readonly decimal _rate;

    public TaxCalculator(decimal rate)
    {
        _rate = rate;
    }

    public decimal CalculateTax(decimal amount)
    {
        return Math.Round(_rate * amount, 2);
    }
}</pre>
<p>Now, one or more classes might need to use an <code>ITaxCalculator</code> implementation to fulfill their responsibility (such as calculating the total price for a shopping cart). We can say that an implementation of <code>ITaxCalculator</code> is a <em>dependency</em> to them.</p>
<p>Like many IoC containers, Ninject uses a central object (which it calls the <em>kernel</em>) to provide concrete implementations of dependencies at run-time. The <code>Standard Kernel</code> is the default implementation of such an object. Let&#39;s see it in action:</p>
<pre class="brush:csharp">using (IKernel kernel = new StandardKernel())
{
    kernel.Bind&lt;ITaxCalculator&gt;()
          .To&lt;TaxCalculator&gt;()
          .WithConstructorArgument(&quot;rate&quot;, .2M);

    var tc = kernel.Get&lt;ITaxCalculator&gt;();
    Assert.Equal(20M, tc.CalculateTax(100M));
}</pre>
<p>&nbsp;</p>
<p>As you can see, through a fluent interface we are instructing the kernel how to <em>bind</em> (resolve) requests for a <code>ITaxCalculator</code> to a <code>TaxCalculator</code> class (a concrete implementation), passing to its constructor a given tax rate (20% in this case).</p>
<p>The example continues showing how a client can retrieve an implementation of the service through the kernel (via the <code>Get()</code> method) and use it.</p>
<h3>Some Magic</h3>
<p>You might argue that the little example above is far from impressing. So let&rsquo;s now see Ninject performing something more clever.</p>
<p>Suppose we have a <code>Sale</code> class modeling a ongoing transaction on a ecommerce site. Such a class in our example depends on a <code>ITaxCalculator</code>to compute the final price of the shopping cart.</p>
<pre class="brush:csharp">public class Sale
{
    private readonly ITaxCalculator taxCalculator;

    public Sale(ITaxCalculator taxCalculator)
    {
        this.taxCalculator = taxCalculator;
    }

    // more stuff....

    public decimal GetTotal()
    {
	// use the tax calculator to calculate the total
    }
}</pre>
<p>We might create the sale in the obvious way, based on the preceding example:</p>
<pre class="brush:csharp">kernel.Bind&lt;ITaxCalculator&gt;()
          .To&lt;TaxCalculator&gt;()
          .WithConstructorArgument(&quot;rate&quot;, .2M);
var sale = new Sale(kernel.Get&lt;ITaxCalculator&gt;());&gt;</pre>
<p>More interestingly, it&#39;s possible to let Ninject to find out how a <code>Sale</code> should be built based on the binding information it has received:</p>
<pre class="brush:csharp">kernel.Bind&lt;ITaxCalculator&gt;()
          .To&lt;TaxCalculator&gt;()
          .WithConstructorArgument(&quot;rate&quot;, .2M);
var sale = kernel.Get&lt;Sale&gt;();</pre>
<p>Ninject is smart enough to build a Sale class for us taking care of fulfilling the dependencies behind the scenes. This an example of <em>autowiring</em>, a most convenient feature of many IoC containers.</p>
<p><em>Go to <a href="http://stefanoricciardi.com/2011/02/04/ninject-mini-tutorial-part-2//">Part 2</a></em></p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2011/01/21/ninject-mini-tutorial-part-1/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2011/01/21/ninject-mini-tutorial-part-1/" border="0" alt="kick it on DotNetKicks.com" /></a></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2011/01/21/ninject-mini-tutorial-part-1/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Project Euler Problem 18 in F#</title>
		<link>http://stefanoricciardi.com/2011/01/10/project-euler-problem-18-in-f/</link>
		<comments>http://stefanoricciardi.com/2011/01/10/project-euler-problem-18-in-f/#comments</comments>
		<pubDate>Mon, 10 Jan 2011 12:18:39 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[F#]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[functional]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1317</guid>
		<description><![CDATA[2011 brings us yet another Project Euler problem to tackle: this time is&#160;Problem 18,&#160;one of the most interesting that I&#39;ve solved so far: By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2011%2F01%2F10%2Fproject-euler-problem-18-in-f%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2011%2F01%2F10%2Fproject-euler-problem-18-in-f%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>2011 brings us yet another Project Euler problem to tackle: this time is&nbsp;<a href="http://projecteuler.net/index.php?section=problems&amp;id=18">Problem 18</a>,&nbsp;one of the most interesting that I&#39;ve solved so far:</p>
<blockquote>
<p>By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.</p>
<p align="center"><b>3</b> <br />
		<b>7</b> 4 <br />
		2 <b>4</b> 6 <br />
		8 5 <b>9</b> 3</p>
<p>That is, 3 + 7 + 4 + 9 = 23.</p>
<p>Find the maximum total from top to bottom of the triangle below:</p>
<p align="center">75 <br />
		95 64 <br />
		17 47 82 <br />
		18 35 87 10 <br />
		20 04 82 47 65 <br />
		19 01 23 75 03 34 <br />
		88 02 77 73 07 63 67 <br />
		99 65 04 28 06 16 70 92 <br />
		41 41 26 56 83 40 80 70 33 <br />
		41 48 72 33 47 32 37 16 94 29 <br />
		53 71 44 65 25 43 91 52 97 51 14 <br />
		70 11 33 28 77 73 17 78 39 68 17 57 <br />
		91 71 52 38 17 14 91 43 58 50 27 29 48 <br />
		63 66 04 68 89 53 67 30 73 16 69 87 40 31 <br />
		04 62 98 27 23 09 70 98 73 93 38 53 60 04 23</p>
<p><small><b>NOTE:</b> As there are only 16384 routes, it is possible to solve this problem by trying every route. However, <a href="http://projecteuler.net/index.php?section=problems&amp;id=67">Problem 67</a>, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o) </small></p>
</blockquote>
<h2>Analysis</h2>
<p>This problem is easily solved resorting to <a href="http://en.wikipedia.org/wiki/Dynamic_programming">dynamic programming</a>, which we can loosely describe as decomposing the overall problem into easier sub-problems and combining their solutions to find the final answer.</p>
<p>In our case, if we consider the number associated with each node of the triangle as a cost, the overall problem can be expressed as<em> finding the path with maximum cost from the upper vertex to the bottom row</em>. A generic sub-problem would be the cost to reach the bottom row from a generic node at position <em>i,j</em>.</p>
<p>Given the cost <img src="http://stefanoricciardi.com/blog/wp-content/ql-cache/quicklatex.com-4faccce819a35988e3ddcb44c2ac6908_l3.png" class="ql-img-inline-formula" alt="&#99;&#95;&#123;&#105;&#44;&#106;&#125;" title="Rendered by QuickLaTeX.com" style="vertical-align: -6px;"/> of passing through a given node and the cost <img src="http://stefanoricciardi.com/blog/wp-content/ql-cache/quicklatex.com-b5bf03ee0efde0ed83151b123ead9d6d_l3.png" class="ql-img-inline-formula" alt="&#67;&#95;&#123;&#105;&#44;&#106;&#125;" title="Rendered by QuickLaTeX.com" style="vertical-align: -6px;"/> of reaching the bottom row from that particular node, we can define the following truth:</p>
<p>
<p class="ql-center-displayed-equation" style="line-height: 19px;"><span class="ql-right-eqno"> &nbsp; </span><span class="ql-left-eqno"> &nbsp; </span><img src="http://stefanoricciardi.com/blog/wp-content/ql-cache/quicklatex.com-ee11802d95580493d2bf20d7eeb2bf0e_l3.png"class="ql-img-displayed-equation" alt="&#92;&#91;&#67;&#95;&#123;&#105;&#44;&#106;&#125;&#32;&#61;&#32;&#99;&#95;&#123;&#105;&#44;&#106;&#125;&#32;&#43;&#32;&#109;&#97;&#120;&#40;&#67;&#95;&#123;&#105;&#43;&#49;&#44;&#106;&#125;&#44;&#32;&#67;&#95;&#123;&#105;&#43;&#49;&#44;&#106;&#43;&#49;&#125;&#41;&#92;&#93;" title="Rendered by QuickLaTeX.com"/></p>
</p>
<p>or, in other words, from each node <em>i,j</em>&nbsp;the cost of reaching the bottom is equal to the cost of the node itself plus the maximum path between one of the two adjacent nodes from the row below.</p>
<p>Let&#39;s confirm why this is the case with the help of the following figure: consider for example the first node from the left in the fourteenth (last-but-one) row (having cost <strong>63</strong>): from there you can move to the bottom either going to node <strong>04</strong> or node <strong>62</strong>. Clearly, if we want to pick the highest cost, we need to pick <strong>62 </strong>(and we mark this choice with a grey line). The overall cost to reach the bottom from that node is thus 63 + max (04, 62) = <strong>125</strong>.</p>
<p>Let&rsquo;s consider now the second node from that row (<strong>66)</strong>. From there, we have to choose between node <strong>62</strong> and <strong>98</strong>: the highest cost path from there is thus 66 + max(62, 98) = <strong>164</strong>. We can continue for all the nodes in the row to find the highest cost path from each node; the solution to such sub-problems is indicated in gray close to each node.</p>
<p><a href="http://stefanoricciardi.com/blog/wp-content/uploads/2010/12/ProjectEuler18_2rows.png"><img alt="ProjectEuler18_2rows" border="0" height="89" src="http://stefanoricciardi.com/blog/wp-content/uploads/2010/12/ProjectEuler18_2rows_thumb.png" style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="ProjectEuler18_2rows" width="454" /></a></p>
<p>Having solved all sub-problems for row 14, we can now consider the row immediately above. In the following figure, I have replaced row 14 with the solutions of the sub-problems that we had just solved; the row above is row 13. Please note how we don&rsquo;t care about row 15 anymore: its contribution to the overall problem is already captured in each sub-problems&rsquo; solution for row 14! Hence, we proceed in a similar way to solve the sub-problems for the row 13 just as we did for row 14:</p>
<p><a href="http://stefanoricciardi.com/blog/wp-content/uploads/2010/12/ProjectEuler18_2rows1.png"><img alt="ProjectEuler18_2rows" border="0" height="68" src="http://stefanoricciardi.com/blog/wp-content/uploads/2010/12/ProjectEuler18_2rows_thumb1.png" style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="ProjectEuler18_2rows" width="529" /></a></p>
<p>We continue to follow a similar pattern moving upwards row after row, until we reach the tip of the triangle, always considering two rows at a time.</p>
<h2>Solution</h2>
<pre class="brush:fsharp">#light

let a = Array2D.zeroCreate&lt;int&gt; 15 15

a.[0,0] &lt;- 75
a.[1,0] &lt;- 95
a.[1,1] &lt;- 64
a.[2,0] &lt;- 17
a.[2,1] &lt;- 47
a.[2,2] &lt;- 82
a.[3,0] &lt;- 18
// other initializations omitted for clarity
// full listing available on Github
// (https://github.com/stefanoric/YAPEFSHARP)
a.[14,10] &lt;- 38
a.[14,11] &lt;- 53
a.[14,12] &lt;- 60
a.[14,13] &lt;- 04
a.[14,14] &lt;- 23 

let costs = Array2D.zeroCreate&lt;int&gt; 15 15

// costs for bottom row is the same as bottom row values
Array2D.blit a 14 0 costs 14 0 1 15 |&gt; ignore

let max a b = if a &gt; b then a else b

for i in 13 .. -1 .. 0 do
    for j in 0 .. i do
        costs.[i,j] &lt;- a.[i,j] + max costs.[i+1,j] costs.[i+1, j+1]

let result () =
    costs.[0,0]</pre>
<p>Most of the code for this solution is needed just to initialize the two dimensional array containing the triangle. For reading convenience, I have skipped most of the uninteresting rows, but you can find the complete solution on <a href="https://github.com/stefanoric/YAPEFSHARP">Github</a>.</p>
<p>So, we have a matrix (2D array) for the cost of each nodes and another matrix for the solutions of the sub-problems associated to each node. Trivially, the costs and the solutions coincide for the bottom row (note the handy <code>Array2D.blit</code> function to copy a whole row from one matrix to the other).</p>
<p>Then, with a loop we move backward from the last-but-one row up to the tip of the triangle calculating the sub-problems solutions as explained above.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2011/01/10/project-euler-problem-18-in-f/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2011/01/10/project-euler-problem-18-in-f/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a rev="vote-for" href="http://dotnetshoutout.com/Project-Euler-Problem-18-in-F-Stefano-Ricciardi" class="broken_link"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2011%2F01%2F10%2Fproject-euler-problem-18-in-f%2F" style="border:0px"/></a></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2011/01/10/project-euler-problem-18-in-f/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Project Euler Problem 17 in F#</title>
		<link>http://stefanoricciardi.com/2010/12/16/project-euler-problem-17-in-f/</link>
		<comments>http://stefanoricciardi.com/2010/12/16/project-euler-problem-17-in-f/#comments</comments>
		<pubDate>Thu, 16 Dec 2010 15:33:52 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[F#]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[functional]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1296</guid>
		<description><![CDATA[   ]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F12%2F16%2Fproject-euler-problem-17-in-f%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F12%2F16%2Fproject-euler-problem-17-in-f%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Project Euler problem 17 turned out to be quite an easy one.</p>
<blockquote>
<p>If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.</p>
<p>If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?</p>
<p><small>NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of &quot;and&quot; when writing out numbers is in compliance with British usage.</small></p>
</blockquote>
<h2>Solution</h2>
<p>The solution this time is almost trivial:</p>
<ul>
<li>&quot;<em>Zero</em>&quot; is considered to have 0 length (it will be obvious later on why this is the case)</li>
<li>Numbers from <strong>1</strong> to <strong>19</strong> have their own unique names (i.e. they are not composed by putting together more words)</li>
<li>Numbers from <strong>20</strong> to<strong> 99</strong> are combined putting together a word like &quot;<em>thirty</em>&quot; and a number from 0 to 9. If the number is zero, we don&#39;t add anything (we don&#39;t say <em>&quot;twenty and zero&quot;</em>)</li>
<li>Numbers from <strong>100 </strong>to <strong>999 </strong>are combined putting together a words like &quot;<em>two hundred and</em>&quot; plus a number from 0 to 99 composed as explained above. Exact multiples of <strong>100 </strong>are exception in that they don&#39;t have another trailing number (again, we don&#39;t say &quot;<em>two hundred and zero</em>&quot;).</li>
</ul>
<pre class="brush:fsharp">#light

let thousand    = &quot;oneThousand&quot;
let hundred     = &quot;hundred&quot;
let hundred_and = &quot;hundredAnd&quot;

let zero_to_nine = new System.Collections.Generic.Dictionary&lt;int, string=&quot;&quot;&gt;()
zero_to_nine.[0] &lt;- &quot;&quot;
zero_to_nine.[1] &lt;- &quot;one&quot;
zero_to_nine.[2] &lt;- &quot;two&quot;
zero_to_nine.[3] &lt;- &quot;three&quot;
zero_to_nine.[4] &lt;- &quot;four&quot;
zero_to_nine.[5] &lt;- &quot;five&quot;
zero_to_nine.[6] &lt;- &quot;six&quot;
zero_to_nine.[7] &lt;- &quot;seven&quot;
zero_to_nine.[8] &lt;- &quot;eight&quot;
zero_to_nine.[9] &lt;- &quot;nine&quot;

let ten_to_nineteen =  new System.Collections.Generic.Dictionary&lt;int, string=&quot;&quot;&gt;()
ten_to_nineteen.[10] &lt;- &quot;ten&quot;
ten_to_nineteen.[11] &lt;- &quot;eleven&quot;
ten_to_nineteen.[12] &lt;- &quot;twelve&quot;
ten_to_nineteen.[13] &lt;- &quot;thirteen&quot;
ten_to_nineteen.[14] &lt;- &quot;fourteen&quot;
ten_to_nineteen.[15] &lt;- &quot;fifteen&quot;
ten_to_nineteen.[16] &lt;- &quot;sixteen&quot;
ten_to_nineteen.[17] &lt;- &quot;seventeen&quot;
ten_to_nineteen.[18] &lt;- &quot;eighteen&quot;
ten_to_nineteen.[19] &lt;- &quot;nineteen&quot;

let twenty_to_ninety = new System.Collections.Generic.Dictionary&lt;int, string=&quot;&quot;&gt;()
twenty_to_ninety.[20] &lt;- &quot;twenty&quot;
twenty_to_ninety.[30] &lt;- &quot;thirty&quot;
twenty_to_ninety.[40] &lt;- &quot;forty&quot;
twenty_to_ninety.[50] &lt;- &quot;fifty&quot;
twenty_to_ninety.[60] &lt;- &quot;sixty&quot;
twenty_to_ninety.[70] &lt;- &quot;seventy&quot;
twenty_to_ninety.[80] &lt;- &quot;eighty&quot;
twenty_to_ninety.[90] &lt;- &quot;ninety&quot;

let len s = String.length s

let calculate_letters_under_one_hundred n =
    match n with
        | x when x &lt; 10 -&gt; len zero_to_nine.[x]
        | x when x &lt; 20 -&gt; len ten_to_nineteen.[x]
        | x when x &lt; 100 -&gt; len twenty_to_ninety.[((x / 10) * 10)] + len zero_to_nine.[(x % 10)]
        | _ -&gt; failwith &quot;Number is too big!&quot;

let calculate_letters n =
    match n with
        | x when x &lt; 100 -&gt; calculate_letters_under_one_hundred x
        | x when ((x &lt; 1000) &amp;&amp; (x % 100 = 0)) -&gt; len zero_to_nine.[(x / 100)] + len hundred
        | x when x &lt; 1000 -&gt; len zero_to_nine.[(x / 100)] + len hundred_and +  calculate_letters_under_one_hundred (x % 100)
        | 1000 -&gt; len thousand
        | _ -&gt; failwith &quot;Numer is too big!&quot;

let all_letters_up_to n =
    List.sumBy (fun i -&gt; calculate_letters i) [1..n]
</pre>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2010/12/16/project-euler-problem-17-in-f/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2010/12/16/project-euler-problem-17-in-f/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a href="http://dotnetshoutout.com/Project-Euler-Problem-17-in-F-Stefano-Ricciardi" rev="vote-for" class="broken_link"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F12%2F16%2Fproject-euler-problem-17-in-f%2F" style="border:0px" /></a></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/12/16/project-euler-problem-17-in-f/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Project Euler Problem 16 in F#</title>
		<link>http://stefanoricciardi.com/2010/12/12/project-euler-problem-16-in-f/</link>
		<comments>http://stefanoricciardi.com/2010/12/12/project-euler-problem-16-in-f/#comments</comments>
		<pubDate>Sun, 12 Dec 2010 14:10:15 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[functional]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1282</guid>
		<description><![CDATA[It&#8217;s time for another Project Euler exercise. This time around it&#8217;s problem 16: 215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 21000? Analysis I have tried to found an elegant way to [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F12%2F12%2Fproject-euler-problem-16-in-f%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F12%2F12%2Fproject-euler-problem-16-in-f%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>It&rsquo;s time for another Project Euler exercise. This time around it&rsquo;s problem 16:</p>
<blockquote>
<p>2<sup>15</sup> = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.</p>
<p>What is the sum of the digits of the number 2<sup>1000</sup>?</p>
</blockquote>
<h2>Analysis</h2>
<p>I have tried to found an elegant way to solve this problem at a mathematical level, but I couldn&#39;t gain any insight relating powers of 2 to their representation in base 10 (I&#39;d love to know if such a thing exists). Therefore I resorted to solve this problem with brute force.</p>
<p>Luckily F# (and now all other .NET 4.0 cousin languages) sports the<code> BigInteger</code> numeric type which helps tackling such huge numbers.</p>
<p>There are basically two approaches to solve this problem:</p>
<ul>
<li>Transform the result of exponentiation into a <em>string </em>and iterate through the string adding up all the individual digits, or</li>
<li>Do without strings, and decompose the big number into the individual digits on my own.</li>
</ul>
<p>I have decided to take the second route because it seemed like a more interesting exercise (the first approach could probably lead to a one-liner). <sup>[<a href="#project-euler-problem-16-in-f-n-1" class="footnoted" id="to-project-euler-problem-16-in-f-n-1">1</a>]</sup>.</p>
<p>Let&rsquo;s consider a generic number <em>n</em> and consider how we can describe it as a sum of powers of 10:</p>
<p>
<p class="ql-center-displayed-equation" style="line-height: 53px;"><span class="ql-right-eqno"> &nbsp; </span><span class="ql-left-eqno"> &nbsp; </span><img src="http://stefanoricciardi.com/blog/wp-content/ql-cache/quicklatex.com-4ea1e3a6cdfb46f446deea4ce5faa1a1_l3.png"class="ql-img-displayed-equation" alt=" &#92;&#91; &#110;&#32;&#61;&#32;&#92;&#115;&#117;&#109;&#95;&#123;&#105;&#61;&#48;&#125;&#94;&#107;&#32;&#100;&#95;&#105;&#49;&#48;&#94;&#105; &#92;&#93; " title="Rendered by QuickLaTeX.com"/></p>
</p>
<p>For example</p>
<p>
<p class="ql-center-displayed-equation" style="line-height: 18px;"><span class="ql-right-eqno"> &nbsp; </span><span class="ql-left-eqno"> &nbsp; </span><img src="http://stefanoricciardi.com/blog/wp-content/ql-cache/quicklatex.com-fa02da8a8e9cec89a5809289b7db483e_l3.png"class="ql-img-displayed-equation" alt=" &#92;&#91;&#32;&#52;&#50;&#51;&#32;&#61;&#32;&#51;&#32;&#92;&#99;&#100;&#111;&#116;&#32;&#49;&#48;&#94;&#48;&#32;&#43;&#32;&#50;&#92;&#99;&#100;&#111;&#116;&#32;&#49;&#48;&#94;&#49;&#32;&#43;&#32;&#52;&#32;&#92;&#99;&#100;&#111;&#116;&#32;&#49;&#48;&#94;&#50;&#32;&#92;&#93; " title="Rendered by QuickLaTeX.com"/></p>
</p>
<p>and <em>k = 2,</em> <em>d<sub>0</sub> = 3</em>, <em>d<sub>1</sub> = 2</em>, and <em>d<sub>2</sub> = 4</em></p>
<p>&nbsp;</p>
<p>So, given a generic number <em>n</em>, we need to find the highest power of ten ( <em>k </em>) such that <img src="http://stefanoricciardi.com/blog/wp-content/ql-cache/quicklatex.com-c669e5dc42c92019f21d9a504d0c86b9_l3.png" class="ql-img-inline-formula" alt="&#32;&#92;&#102;&#114;&#97;&#99;&#123;&#110;&#125;&#123;&#49;&#48;&#94;&#107;&#125;&#32;&#62;&#32;&#48;" title="Rendered by QuickLaTeX.com" style="vertical-align: -8px;"/></p>
<p>(logarithms will help us there). After <em>k</em> is found, we can start diving n by <em>10<sup>k</sup></em> to find <em>d<sub>k</sub> </em>and use the reminder of the division to calculate <em>d<sub>k-1</sub></em> and so forth until we reach <em>d<sub>0</sub></em>.</p>
<h2>Solution</h2>
<pre class="brush:fsharp">#light

open System
open System.Numerics

let rec decompose_rec n power_of_ten accu =
    match power_of_ten with
        | i when i = 1I -&gt; accu @ [n]
        |_ -&gt;
            let d = n / power_of_ten
            let digits = accu @ [d]
            decompose_rec (n - (d * power_of_ten)) (power_of_ten / 10I) digits

let decompose n =
    let power = floor (log10 (float n))
    let initial_power_of_ten = BigInteger.Pow(10I, int32 power)
    decompose_rec n initial_power_of_ten []

let sum_digits n =
    decompose n |&gt; List.sum
</pre>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2010/12/12/project-euler-problem-16-in-f/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2010/12/12/project-euler-problem-16-in-f/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a href="http://dotnetshoutout.com/Project-Euler-Problem-16-in-F-Stefano-Ricciardi" rev="vote-for"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F12%2F12%2Fproject-euler-problem-16-in-f%2F" style="border:0px" /></a></p>

<ol class="footnotes">
	<li class="footnote" id="project-euler-problem-16-in-f-n-1"><strong><sup>[1]</sup></strong> A recruiter for a very big company once asked me something very similar during an interview as a coding exercise <a class="note-return" href="#to-project-euler-problem-16-in-f-n-1">&#x21A9;</a></li></ol>
]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/12/12/project-euler-problem-16-in-f/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Project Euler Problem 15 in F#</title>
		<link>http://stefanoricciardi.com/2010/12/01/project-euler-problem-15-in-fsharp/</link>
		<comments>http://stefanoricciardi.com/2010/12/01/project-euler-problem-15-in-fsharp/#comments</comments>
		<pubDate>Wed, 01 Dec 2010 15:43:58 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[functional]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1248</guid>
		<description><![CDATA[With Project Euler Problem 15 we approach the fascinating world of graphs (but, as we shall see, only in a very tangential fashion): Starting in the top left corner of a 2&#215;2 grid, there are 6 routes (without backtracking) to the bottom right corner. How many routes are there through a 20&#215;20 grid? Analysis With [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F12%2F01%2Fproject-euler-problem-15-in-fsharp%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F12%2F01%2Fproject-euler-problem-15-in-fsharp%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>With <a href="http://projecteuler.net/index.php?section=problems&amp;id=15">Project Euler Problem 15</a> we approach the fascinating world of graphs (but, as we shall see, only in a very tangential fashion):</p>
<blockquote>
<p>Starting in the top left corner of a 2&#215;2 grid, there are 6 routes (without backtracking) to the bottom right corner.</p>
<p><img alt="alt" src="http://projecteuler.net/project/images/p_015.gif" style="display: block; float: none; margin-left: auto; margin-right: auto" /></p>
<p>How many routes are there through a 20&#215;20 grid?</p>
</blockquote>
<h2>Analysis</h2>
<p>With pen and paper the fact that a 2&#215;2 grid has 6 possible routes can be easily confirmed. However, as soon as the grid size grows, it&#39;s simply not practical to start drawing all the possible ways to reach the lowest right corner from the top left one.</p>
<p>In order to find a general solution, it helps trying a <a href="http://en.wikipedia.org/wiki/Dynamic_programming">dynamic programming</a> approach: we first try to solve a smaller problem and then combine the solutions of more sub-problems to find the overall answer.</p>
<p>The smallest problem that we can consider is the number of possible routes in a 1&#215;1 grid. What could be simpler? Considering all the three possible starting corners of such a grid we can see that:</p>
<ul>
<li>From both the bottom-left and the top-right corner there&#39;s only one possible route to the destination.</li>
<li>From the top-left corner there are trivially two possible routes.</li>
</ul>
<p>In the picture below, I have marked for each corners the number of possible routes to the destination for the 1&#215;1 grid:</p>
<p>&nbsp;<img alt="PascalGrid_2x2" border="0" height="222" src="http://stefanoricciardi.com/blog/wp-content/uploads/2010/12/PascalGrid_2x2.png" style="border-right-width: 0px; margin: 10px 0px; display: inline; float: ; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="PascalGrid_2x2" width="180" /></p>
<p>We can now consider the bigger 2&#215;2 grid enclosing the smaller 1&#215;1 grid representing the sub-problem we solved earlier:</p>
<ul>
<li>Both points on the outer sides of the grid have only one possible route to the destination. In fact, from there you can only proceed along the edge. So, we mark both of these points with 1.</li>
<li>Let&rsquo;s now consider the point immediately above the bottom left one on the grid: from this point we can either move down (to the point that we just marked with a &ldquo;1&rdquo;) or right to the point of the 1&#215;1 grid that we had marked with a &ldquo;2&rdquo; previously. Hence, from this point we have 1 possible route if we decide to go down <em>or</em> 2 possible routes if we decide to go right: that makes 3 possible routes that can lead from this point to the destination.</li>
</ul>
<p>We can generalize and deduce that <em>for each point in the grid, the number of possible routes to the destination is equal to the sum of the routes available from the point immediately down and the point immediately right</em> (points on the outer edge having only 1 possible route). This is the key to solve this problem for any kind of grid.</p>
<p>So, we have informally demonstrated the result for the 2&#215;2 grid:</p>
<p><img alt="PascalGrid_4x4" border="0" height="297" src="http://stefanoricciardi.com/blog/wp-content/uploads/2010/12/PascalGrid_4x4.png" style="border-right-width: 0px; margin: 10px 0px; display: inline; float: ; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="PascalGrid_4x4" width="274" /></p>
<p>And similarly we can resolve the problem for a 3&#215;3 grid:<a href="http://stefanoricciardi.com/blog/wp-content/uploads/2010/12/PascalGrid.png"><img alt="PascalGrid" border="0" height="412" src="http://stefanoricciardi.com/blog/wp-content/uploads/2010/12/PascalGrid_thumb.png" style="border-right-width: 0px; margin: 10px 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="PascalGrid" width="388" /></a></p>
<p>Now, if you look closely at the patterns of the possible routes for each point in the grid, you may recognize what in Italy we call <em>Il triangolo di Tartaglia (Tartaglia&rsquo;s Triangle)</em>, which everywhere else in the world is most probably known as Pascal&#39;s Triangle:</p>
<p><img alt="PascalTriangle" border="0" height="135" src="http://stefanoricciardi.com/blog/wp-content/uploads/2010/12/PascalTriangle.png" style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="PascalTriangle" width="236" /></p>
<p>(note that the triangle obviously continues <em>ad infinitum</em>).</p>
<p>The solution for a square grid of any size lies in the vertical diagonal (if you excuse the quasi-oxymoron), that is 1, 2, 6, 20, etc&hellip;. If we start counting rows from the top, first row being row 0, second row being row 1 and so on, and columns from the left also starting from 0, we can see that for a square grid of size <em>n</em>, the number of routes is given by the item in the&nbsp;<em>n</em> column within the 2*<em>n </em>row.</p>
<p>Now, it would be trivial, if somehow boring, to solve the problem for a 20&#215;20 grid using a spreadsheet. All you have to do is to create the 20 x 2 = 40 rows of the Pascal triangle (with some copy and paste of the right formula for each cell), and pick the 20<sup>th</sup> element from that road.</p>
<p>However, you don&#39;t actually have to create the whole triangle: the values of each row can be calculated using they <a href="http://en.wikipedia.org/wiki/Binomial_coefficient">binomial expansion</a>: for a given row <em>r, </em>the value at column <em>c</em> is given by the following formula:</p>
<p>
<p class="ql-center-displayed-equation" style="line-height: 43px;"><span class="ql-right-eqno"> &nbsp; </span><span class="ql-left-eqno"> &nbsp; </span><img src="http://stefanoricciardi.com/blog/wp-content/ql-cache/quicklatex.com-494f202bf56cb0708f8fd8032c75edc9_l3.png"class="ql-img-displayed-equation" alt=" &#92;&#91; &#118;&#40;&#99;&#41;&#32;&#61;&#32;&#92;&#98;&#105;&#110;&#111;&#109;&#123;&#114;&#125;&#123;&#99;&#125;&#32;&#61;&#32;&#92;&#102;&#114;&#97;&#99;&#123;&#114;&#125;&#123;&#99;&#33;&#40;&#114;&#45;&#99;&#41;&#33;&#125;&#32; &#92;&#93; " title="Rendered by QuickLaTeX.com"/></p>
</p>
<p>Perhaps more interestingly, you can calculate the same value without resorting to the factorial by using the following recursive formula (where <em>r&#39;&nbsp;</em>is the row number <em>+1</em> and &nbsp;<em>c</em> is the column index):</p>
<p>
<p class="ql-center-displayed-equation" style="line-height: 65px;"><span class="ql-right-eqno"> &nbsp; </span><span class="ql-left-eqno"> &nbsp; </span><img src="http://stefanoricciardi.com/blog/wp-content/ql-cache/quicklatex.com-bc3e0098d27c5167123ffbd1605e5b2b_l3.png"class="ql-img-displayed-equation" alt=" &#92;&#98;&#101;&#103;&#105;&#110;&#123;&#97;&#108;&#105;&#103;&#110;&#42;&#125; &#118;&#40;&#99;&#41;&#32;&#38;&#61;&#32;&#118;&#40;&#99;&#45;&#49;&#41;&#32;&#92;&#102;&#114;&#97;&#99;&#123;&#114;&#39;&#45;&#99;&#125;&#123;&#99;&#125;&#92;&#92; &#118;&#40;&#48;&#41;&#32;&#38;&#61;&#32;&#49; &#92;&#101;&#110;&#100;&#123;&#97;&#108;&#105;&#103;&#110;&#42;&#125; " title="Rendered by QuickLaTeX.com"/></p>
</p>
<h2>Solution</h2>
<p>So, after all this analysis, the solution comes up to be quite simple and maybe not that interesting <em>per se</em>. The recursive formula to calculate the values from the triangle&#39;s rows fits naturally the F# pattern matching:</p>
<pre class="brush:fsharp">#light

let rec pascal_item row_plus_one column =
    match column with
    | 0L -&gt; 1L
    | _-&gt; (row_plus_one-column) * (pascal_item row_plus_one (column-1L)) / column

let number_of_routes grid_size =
    pascal_item (int64(2*grid_size + 1)) (int64 grid_size)</pre>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2010/12/01/project-euler-problem-15-in-fsharp/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2010/12/01/project-euler-problem-15-in-fsharp/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a href="http://dotnetshoutout.com/Project-Euler-Problem-15-in-F-Stefano-Ricciardi" rev="vote-for" class="broken_link"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F12%2F01%2Fproject-euler-problem-15-in-fsharp%2F" style="border:0px" /></a></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/12/01/project-euler-problem-15-in-fsharp/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Project Euler Problem 14 in F#</title>
		<link>http://stefanoricciardi.com/2010/11/23/project-euler-problem-14-in-f/</link>
		<comments>http://stefanoricciardi.com/2010/11/23/project-euler-problem-14-in-f/#comments</comments>
		<pubDate>Tue, 23 Nov 2010 13:35:34 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[functional]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1228</guid>
		<description><![CDATA[Project Euler Problem 14 introduces the fascinating Collatz Conjecture: Take any natural number n. If n is even, divide it by 2 to get n / 2, if n is odd multiply it by 3 and add 1 to obtain 3n + 1. Repeat the process indefinitely. The conjecture is that no matter what number [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F11%2F23%2Fproject-euler-problem-14-in-f%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F11%2F23%2Fproject-euler-problem-14-in-f%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p><a href="http://projecteuler.net/index.php?section=problems&amp;id=14">Project Euler Problem 14</a> introduces the fascinating <a href="http://en.wikipedia.org/wiki/Collatz_conjecture">Collatz Conjecture</a>:</p>
<blockquote><p>Take any natural number n. If n is even, divide it by 2 to get n / 2, if n is odd multiply it by 3 and add 1 to obtain 3n + 1. Repeat the process indefinitely. The conjecture is that no matter what number you start with, you will always eventually reach 1.</p></blockquote>
<p>The Euler problem to be resolved is phrased as follows:</p>
<blockquote>
<p>The following iterative sequence is defined for the set of positive integers:</p>
<p>n &ndash;&gt; n/2 (n is even) <br />
		n &ndash;&gt; 3n + 1 (n is odd)</p>
<p>Using the rule above and starting with 13, we generate the following sequence:</p>
<p>13 &ndash;&gt; 40 &ndash;&gt; 20 &ndash;&gt; 10 &ndash;&gt; 5 &ndash;&gt; 16 &ndash;&gt; 8 &ndash;&gt;&nbsp; 4 &ndash;&gt; 2 &ndash;&gt;&nbsp; 1</p>
<p>It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.</p>
<p>Which starting number, under one million, produces the longest chain?</p>
</blockquote>
<p>As with many other Project Euler problems, we are requested to generate a sequence (in this case a sequence of &ldquo;Collatz sequences&rdquo;) and to single out one item matching a certain criteria. In this particular case, we need to create Collatz sequences for all numbers under 1 million and find out the longest one.</p>
<h2>Solution</h2>
<p>The basic algorithm has the following shape:</p>
<pre class="brush:fsharp">let is_odd x =
    x % 2L = 1L

let rec naive_sequence n (partial:int64 list) =
    match n with
        | 1L -&gt; partial @ [1L]
        | x when is_odd x -&gt; naive_sequence ((3L*x) + 1L) (partial @ [n])
        |_ -&gt; naive_sequence (n/2L) (partial @ [n])
</pre>
<p>Using this recursive function, we could easily generate Collatz sequences for arbitrarily large numbers. But the performance would soon degrade when we start building sequence for numbers bigger than about 10 thousands.</p>
<p>In the process of generating all the sequences from 1 to 1 million, however, it&rsquo;s easy to see that for each sequence that we build, there are a lot of subsequences that are identical, which are being calculated over and over.</p>
<p>Consider for example the two sequences having 5 and 24 as starting numbers respectively:</p>
<p><strong>5 &ndash;&gt; 16 &ndash;&gt; 8 &ndash;&gt; 4 &ndash;&gt; 2 &ndash;&gt; 1</strong></p>
<p>24 &ndash;&gt; 12 &ndash;&gt; 6 &ndash;&gt; 3 &ndash;&gt; 10 &ndash;&gt; <strong>5 &ndash;&gt; 16 &ndash;&gt; 8 &ndash;&gt; 4 &ndash;&gt; 2 &ndash;&gt; 1</strong></p>
<p>As you can see, after a few iterations the sequence starting from 24 converges to the sequence starting at 5, which we have already calculated! (see <a href="http://upload.wikimedia.org/wikipedia/commons/a/ad/Collatz-graph-all-30-no27.svg">this image</a>&nbsp;from Wikipedia for a pictorial representation of this behavior)</p>
<p>As you would have guessed by now, the key to solve this problem is precisely <em>caching</em> the subsequences that are being calculated, so that the partial results can be reused for subsequent iterations.</p>
<p>So, with these considerations in mind, we can have a look at the final solution:</p>
<pre class="brush:fsharp">#light

open System.Collections.Generic

let is_odd x =
    x % 2L = 1L

let rec collatz_sequence n (partial:int64 list) (cache: IDictionary&lt;int64, int64 list&gt;) =
    if cache.ContainsKey(n) then
        let result = partial @ cache.[n]
        let sequence_starter = List.head result
        if not(cache.ContainsKey(sequence_starter)) then
            cache.Add(sequence_starter, result) |&gt; ignore
        result
    else
        match n with
        | 1L -&gt;
            let result = partial @ [1L]
            let sequence_starter = List.head result
            cache.Add(sequence_starter, result) |&gt; ignore
            result
        | n when is_odd n -&gt; collatz_sequence ((3L*n) + 1L) (partial @ [n]) cache
        | _ -&gt; collatz_sequence (n/2L) (partial @ [n]) cache

let sequence_cache = new Dictionary&lt;int64, int64 list&gt;()

let calculate_sequence n =
    collatz_sequence n [] sequence_cache

let max_sequence_lengths (max:int64) =
    let all_sequences = [for i in 1L..max -&gt; calculate_sequence i]
    let lengths = List.map List.length all_sequences
    let max = List.max lengths
    let max_index = List.findIndex (fun (x:int64 list) -&gt; x.Length = max) all_sequences
    max_index + 1L
</pre>
<p>As you can see, the basic pattern of the algorithm is still the same. However, we have added a cache to store partial results which dramatically improve the performances (this version resolve the problem on my laptop in about 7 seconds).</p>
<p>The last function <code>max_sequence_lengths </code>is the main loop generating all the sequences, calculating the lengths and picking the sequence with the highest length.</p>
<p>Caching partial results is a common theme in functional programming, and is called <a href="http://en.wikipedia.org/wiki/Memoization">memoization</a>. The example provided above is not one of the cleanest examples of memoization. It turns out that combining memoization and tail recursion is a <a href="http://stackoverflow.com/questions/3459422/combine-memoization-and-tail-recursion">tricky problem</a>.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2010/11/23/project-euler-problem-14-in-f/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2010/11/23/project-euler-problem-14-in-f/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a href="http://dotnetshoutout.com/Project-Euler-Problem-14-in-F-Stefano-Ricciardi" rev="vote-for"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F11%2F23%2Fproject-euler-problem-14-in-f%2F" style="border:0px" /></a></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/11/23/project-euler-problem-14-in-f/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

