<?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; F#</title>
	<atom:link href="http://stefanoricciardi.com/tag/f/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>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>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"><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"><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"><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>
		<item>
		<title>Project Euler Problem 13 in F#</title>
		<link>http://stefanoricciardi.com/2010/11/06/project-euler-problem-13-in-f/</link>
		<comments>http://stefanoricciardi.com/2010/11/06/project-euler-problem-13-in-f/#comments</comments>
		<pubDate>Sat, 06 Nov 2010 21:48:11 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[functional]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Parallel]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1204</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%2F11%2F06%2Fproject-euler-problem-13-in-f%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F11%2F06%2Fproject-euler-problem-13-in-f%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Now that with F# (and .NET 4.0 in general) we have support for big integers through the <code>BigInteger</code> type, <a href="http://projecteuler.net/index.php?section=problems&amp;id=13">Project Euler problem 13</a> has become a trivial one:</p>
<blockquote><p>Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.</p>
<p>
		37107287533902102798797998220837590246510135740250 <br />
		46376937677490009712648124896970078050417018260538 <br />
		74324986199524741059474233309513058123726617309629 <br />
		&#8230; <br />
		53503534226472524250874054075591789781264330331690</p>
</blockquote>
<p>Solution (note that I have removed most of the input numbers to improve readability):</p>
<pre class="brush:fsharp">#light

open System.Linq
open System.Numerics

let numbers =
  [|37107287533902102798797998220837590246510135740250I;
    46376937677490009712648124896970078050417018260538I;
    74324986199524741059474233309513058123726617309629I;
    ...
    53503534226472524250874054075591789781264330331690I|]

let solve_problem_13 () =
    numbers
        .Aggregate(0I, fun (x:BigInteger) (y:BigInteger) -&gt; x + y)
            .ToString().Substring(0, 10)
</pre>
<p>Using Linq, it&#39;s easy to compute the solution with a simple aggregation. Note that I couldn&#39;t use the <code>Sum</code> function directly because it does not have an overload for <code>BigInteger</code> type.</p>
<p>Without support for such big numbers, one could have reasoned that, in order to calculate the first 10 digits of the result, only the first <b>11</b> digits of each number are relevant. With this intuition, the problem would have been tractable using simple <code>long</code>s.</p>
<h2>Parallel version</h2>
<p>Problem 13 is a classical problem that can be resolved using <a href="http://msdn.microsoft.com/en-us/library/ff963547.aspx">parallel aggregation</a>: it can be decomposed into many independent sub-tasks (each calculating the sum of 10 numbers, as an example) and the final result can be obtained aggregating the results from each of them.</p>
<p>With Linq <code>AsParallel</code>, scaling this problem on multiple cores is trivial:</p>
<pre class="brush:fsharp">let solve_problem_13 () =
    numbers
        .AsParallel() // MAKE IT PARALLEL!
            .Aggregate(0I, fun (x:BigInteger) (y:BigInteger) -&gt; x + y)
                .ToString().Substring(0, 10)
</pre>
<p>Of course, with such a trivial problem, you should not expect big performance improvements with a parallel version (indeed, the overhead of splitting the work into different threads might usually <em>lengthen</em> the time it takes to get to the result).</p>
<p><a href="../../tag/euler-problems/" class="broken_link">See all Project Euler problems solutions</a>.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2010/11/06/project-euler-problem-13-in-f/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2010/11/06/project-euler-problem-13-in-f/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a href="http://dotnetshoutout.com/Project-Euler-Problem-13-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%2F06%2Fproject-euler-problem-13-in-f%2F" style="border:0px" /></a></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/11/06/project-euler-problem-13-in-f/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Project Euler Problem 12 in F#</title>
		<link>http://stefanoricciardi.com/2010/10/27/project-euler-problem-12-in-f-2/</link>
		<comments>http://stefanoricciardi.com/2010/10/27/project-euler-problem-12-in-f-2/#comments</comments>
		<pubDate>Wed, 27 Oct 2010 12:40:54 +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=1187</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%2F10%2F27%2Fproject-euler-problem-12-in-f-2%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F10%2F27%2Fproject-euler-problem-12-in-f-2%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>After a brief digression with an <a href="http://stefanoricciardi.com/2010/10/01/a-rpn-calculator-in-f/">RPN Calculator</a>, here we are again with a new Project Euler problem:</p>
<blockquote><p>The sequence of triangle numbers is generated by adding the natural numbers.</p>
<p>So the 7^(th) triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.</p>
<p>The first ten terms would be: <br />
		1, 3, 6, 10, 15, 21, 28, 36, 45, 55, &#8230;</p>
<p>Let us list the factors of the first seven triangle numbers:</p>
<p>
	1: 1 <br />
	3: 1,3 <br />
	6: 1,2,3,6 <br />
	10: 1,2,5,10 <br />
	15: 1,3,5,15 <br />
	21: 1,3,7,21 <br />
	28: 1,2,4,7,14,28</p>
<p>We can see that 28 is the first triangle number to have over five divisors.</p>
<p>What is the value of the first triangle number to have over five hundred divisors?</p>
</blockquote>
<p>Again, this problem is relatively simple to solve and it&#39;s about finding an algorithm with decent performances.</p>
<h2>The naive (slow) solution</h2>
<pre class="brush:fsharp">#light

let triangles =
    Seq.unfold (fun (acc, state) -&gt; Some (acc, (state + acc, state + 1))) (0, 1)
    |&gt; Seq.skip 1 // skip the initial 0

let divides y x =
    x % y = 0

let rec all_factors_slow_rec n i acc =
    match i with
        | 1 -&gt; 1::acc
        | x when divides x n -&gt; all_factors_slow_rec n (x-1) (x::acc)
        | _ -&gt; all_factors_slow_rec n (i-1) acc

let all_factors_slow n =
    all_factors_slow_rec n n []

let find_index m =
    triangles
    |&gt; Seq.map all_factors_slow
    |&gt; Seq.tryFindIndex (fun x -&gt; List.length x &gt;= m)

let resolve_problem_12 =
    let i = find_index 500
    match i with
        | None -&gt; failwith &quot;Cannot resolve problem&quot;
        | Some(i) -&gt;
            let list = triangles |&gt; Seq.take (i+1) |&gt; List.ofSeq
            list.[i]
</pre>
<ul>
<li>Considering that triangle numbers are a mathematical sequence defined as follows: <br />
		<img src="http://l.wordpress.com/latex.php?latex=t_n%20%3D%20t_%7Bn-1%7D%20%2B%20n&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="t_n = t_{n-1} + n" style="vertical-align:-20%;" class="tex" alt="t_n = t_{n-1} + n" /> where <img src="http://l.wordpress.com/latex.php?latex=t_0%20%3D%200&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="t_0 = 0" style="vertical-align:-20%;" class="tex" alt="t_0 = 0" />, then we easily define an F# sequence that yields triangle numbers using <code>Seq.unfold.</code></li>
<li>We then define a function <code>all_factors_slow_rec</code> to calculate all factors (not just primes) of a given number. The slow solution presented in the first listing starts from a number <em>n</em> and then by brute force tries all the numbers down to 1 as a candidate factor.</li>
<li>Once we have these two pieces together, it&#39;s just a matter of enumerating all possible triangle numbers, finding for each their factors (using <code>Seq.map</code>) and finally determining the first triangle number having at least 500 factors (using <code>Seq.tryFindIndex</code>). If <img src="http://l.wordpress.com/latex.php?latex=i&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="i" style="vertical-align:-20%;" class="tex" alt="i" /> is the index of such a number, we then go back to the original sequence of triangles to extract the <img src="http://l.wordpress.com/latex.php?latex=i%5E%7Bth%7D&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="i^{th}" style="vertical-align:-20%;" class="tex" alt="i^{th}" /> element.</li>
</ul>
<h2>An improved version</h2>
<pre class="brush:fsharp">#light

let divides y x =
    x % y = 0

let triangles =
    Seq.unfold (fun (acc, state) -&gt; Some (acc, (state + acc, state + 1))) (0, 1)
    |&gt; Seq.skip 1 // skip the initial 0

let rec all_factors_quick_rec n i factors =
    if divides i n then
        let y = n / i
        if (i &lt; y) then
            all_factors_quick_rec n (i + 1) (i::y::factors)
        elif (i = y) then
            // we have reached the square root value
            i::factors
        else
            factors
    elif i &gt; int (sqrt (float n)) then
        // we are beyond the square root value
        factors
    else
        // try with the next number
        all_factors_quick_rec n (i + 1) factors

let all_factors_quick n =
    all_factors_quick_rec n 1 []

let find_index m =
    triangles
    |&gt; Seq.map all_factors_quick
    |&gt; Seq.tryFindIndex (fun x -&gt; List.length x &gt;= m)

let resolve_problem_12 =
    let i = find_index 500
        match i with
        | None -&gt; failwith &quot;Cannot resolve problem&quot;
        | Some(i) -&gt;
            let list = triangles |&gt; Seq.take (i+1) |&gt; List.ofSeq
            list.[i]
</pre>
<p>The bottleneck of the previous solution is the naive approach to find all the factors of a number. On my machines this solution takes several minutes.</p>
<p>Better performances can be obtained observing that in order to determine all the factors of a number we don&#39;t have try <em>all</em> smaller numbers. As a matter of fact, the following is true (considering <em>n</em> the number to be factorized):</p>
<ul>
<li>if <img src="http://l.wordpress.com/latex.php?latex=n%20%2F%20x%20%3D%20y&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="n / x = y" style="vertical-align:-20%;" class="tex" alt="n / x = y" />, obviously both <em>x</em> and <em>y</em> are factors, so I don&#39;t have to probe <em>y</em> anymore</li>
<li>If I start probing from 2 going up, I can stop probing when I have reached <img src="http://l.wordpress.com/latex.php?latex=%5Csqrt%20n&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="\sqrt n" style="vertical-align:-20%;" class="tex" alt="\sqrt n" />. In fact, any number bigger than <img src="http://l.wordpress.com/latex.php?latex=%5Csqrt%20n&#038;bg=FFFFFF&#038;fg=000000&#038;s=1" title="\sqrt n" style="vertical-align:-20%;" class="tex" alt="\sqrt n" /> must have been already found probing a smaller number.</li>
</ul>
<p>Suppose for example that we have to factor the number 36 (one of the triangle numbers):</p>
<ul>
<li>1 is always a factor -&gt; factors = {<strong>1</strong>, <strong>36</strong>}</li>
<li>2 * 18 = 36 -&gt; factors = {1, 36, <strong>2</strong>, <strong>18</strong>}</li>
<li>3 * 12 = 36 -&gt; factors = {1, 36, 2, 18, <strong>3</strong>, <strong>12</strong> }</li>
<li>4 * 9 = 36 -&gt; factors = {1, 36, 2, 18, 3, 12, <strong>4</strong>, <strong>9</strong>}</li>
<li>5 does not divide -&gt; factors = {1, 36, 2, 18, 3, 12, 4, 9}</li>
<li>6 * 6 = 36 -&gt; factors = {1, 36, 2, 18, 3, 12, 4, 9, <strong>6</strong>}</li>
</ul>
<p>We can stop here because if 7 divided 36 evenly, we would have already found a number <em>x</em> &lt; 6 such that 7 * <em>x</em> = 36.</p>
<p>The improved version runs on my machine in less than 1 second.</p>
<p><em><a href="../../tag/euler-problems/" class="broken_link">See all Project Euler problems solutions</a>. </em></p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2010/10/27/project-euler-problem-12-in-f-2/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2010/10/27/project-euler-problem-12-in-f-2/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a href="http://dotnetshoutout.com/Project-Euler-Problem-12-in-F-Stefano-Ricciardi" rev="vote-for"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F10%2F27%2Fproject-euler-problem-12-in-f-2%2F" style="border: 0px none;" /></a></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/10/27/project-euler-problem-12-in-f-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>A RPN Calculator in F#</title>
		<link>http://stefanoricciardi.com/2010/10/01/a-rpn-calculator-in-f/</link>
		<comments>http://stefanoricciardi.com/2010/10/01/a-rpn-calculator-in-f/#comments</comments>
		<pubDate>Fri, 01 Oct 2010 09:22:36 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[programming praxis]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1164</guid>
		<description><![CDATA[While continuing my journey in F#, after playing with Project Eulero problems for a few weeks, I have come across another excellent&#160; excercise site which goes under the name of Programming Praxis. The first exercise requires to implement a simple calculator using Reverse Polish Notation (RPN). Here follows a simple solution to the problem. Operands [...]]]></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%2F10%2F01%2Fa-rpn-calculator-in-f%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F10%2F01%2Fa-rpn-calculator-in-f%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>While continuing my journey in F#, after playing with Project Eulero problems for a few weeks, I have come across another excellent&nbsp; excercise site which goes under the name of <a href="http://programmingpraxis.com/" target="_blank">Programming Praxis</a>.</p>
<p>The first exercise requires to implement a simple calculator using <a href="http://en.wikipedia.org/wiki/Reverse_Polish_notation" target="_blank">Reverse Polish Notation (RPN)</a>.</p>
<p>Here follows a simple solution to the problem. Operands are pushed onto the stack until an operator is found: at that point the last two operands are popped from the stack, the operator is applied to them and the result is pushed back on the stack.</p>
<pre class="brush:fsharp">#light

let is_operator c =
    match c with
        | &quot;+&quot; | &quot;-&quot; | &quot;*&quot; | &quot;/&quot;  -&gt; true
        | _ -&gt; false

let calculate left operator right =
    match operator with
        | &quot;+&quot; -&gt; left + right
        | &quot;-&quot; -&gt; left - right
        | &quot;*&quot; -&gt; left * right
        | &quot;/&quot; -&gt; left / right
        | _ -&gt; failwith &quot;Unknown operator&quot;

let proc (item:string) (stack:System.Collections.Generic.Stack&amp;lt;double&gt;) =
    if is_operator item then
        let r = stack.Pop()
        let l = stack.Pop()
        let result = calculate l item r
        stack.Push result
    else
        stack.Push(System.Convert.ToDouble(item))

let evaluate (expression:string) =
    let stack = new System.Collections.Generic.Stack&amp;lt;double&gt;()
    let items = expression.Split([|&#39; &#39; |])
    Array.iter (fun i -&gt; proc i stack) items
    stack.Pop()
</pre>
<ul>
<li>We first define a simple function to check whether a given string is to be interpreted as an arithmetic operand. As you can see, we only support basic operators, nothing too fancy.</li>
<li>We then define a function which takes a double, a string (representing an operator) and another double, and returns the result of applying the given operator to the two numbers.</li>
<li>The <code>proc</code> function takes a string, which represent either an operand or an operator, and a stack of operands. <br />
		If the item contained in the string is an operator, two operands are popped from the stack: the first pop is for the right side operand and the second pop is for the left operand; hence, the operator is applied to the two operands and the result is pushed back onto the stack.<br />
		Otherwise, if it&#39;s an operand, it&#39;s first converted from the string format and pushed onto the stack.</li>
<li>Finally, the entrance point to the program is defined with the <code>evaluate</code> function, which 
<ul>
<li>accepts a string containing the overall expression (such as &quot;1 2 + 4 / 5 * 6 -&quot;)</li>
<li>splits the string into an array of token strings</li>
<li>feed each token into the <code>proc</code> function</li>
<li>finally pops the stack with the last operand to yield the result of the operation.</li>
</ul>
</li>
</ul>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2010/10/01/a-rpn-calculator-in-f/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2010/10/01/a-rpn-calculator-in-f/" border="0" alt="kick it on DotNetKicks.com" /></a>
<p><a href="http://dotnetshoutout.com/A-RPN-Calculator-in-F-Stefano-Ricciardi" rev="vote-for"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F10%2F01%2Fa-rpn-calculator-in-f%2F" style="border: 0px none;" /></a></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/10/01/a-rpn-calculator-in-f/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Project Euler Problem 11 in F#</title>
		<link>http://stefanoricciardi.com/2010/09/21/project-euler-problem-11-in-f/</link>
		<comments>http://stefanoricciardi.com/2010/09/21/project-euler-problem-11-in-f/#comments</comments>
		<pubDate>Tue, 21 Sep 2010 14:03:25 +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=1139</guid>
		<description><![CDATA[Project Euler Problem 11 is an interesting one; when addressed with a functional approach it lends itself to be solved using function composition. Let&#39;s have a look at the question and then a possible solution: In the 20&#215;20 grid below, four numbers along a diagonal line have been marked in red. 08 02 22 97 [...]]]></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%2F09%2F21%2Fproject-euler-problem-11-in-f%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F09%2F21%2Fproject-euler-problem-11-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=11">Project Euler Problem 11</a> is an interesting one; when addressed with a functional approach it lends itself to be solved using <i><a href="http://en.wikipedia.org/wiki/Function_composition_%28computer_science%29">function composition</a></i>. Let&#39;s have a look at the question and then a possible solution:</p>
<blockquote><p>In the 20&times;20 grid below, four numbers along a diagonal line have been marked in red. 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 <span style="color: red;">26</span> 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 <span style="color: red;">63 </span>94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 <span style="color: red;">78</span> 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 <span style="color: red;">14</span> 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 The product of these numbers is 26 &times; 63 &times; 78 &times; 14 = 1788696. What is the greatest product of four adjacent numbers in any direction (up, down, left, right, or diagonally) in the 20&times;20 grid?</p></blockquote>
<pre class="brush:fsharp">#light

let numbers =
    array2D [|
      [|08;02;22;97;38;15;00;40;00;75;04;05;07;78;52;12;50;77;91;08|];
      [|49;49;99;40;17;81;18;57;60;87;17;40;98;43;69;48;04;56;62;00|];
      [|81;49;31;73;55;79;14;29;93;71;40;67;53;88;30;03;49;13;36;65|];
      [|52;70;95;23;04;60;11;42;69;24;68;56;01;32;56;71;37;02;36;91|];
      [|22;31;16;71;51;67;63;89;41;92;36;54;22;40;40;28;66;33;13;80|];
      [|24;47;32;60;99;03;45;02;44;75;33;53;78;36;84;20;35;17;12;50|];
      [|32;98;81;28;64;23;67;10;26;38;40;67;59;54;70;66;18;38;64;70|];
      [|67;26;20;68;02;62;12;20;95;63;94;39;63;08;40;91;66;49;94;21|];
      [|24;55;58;05;66;73;99;26;97;17;78;78;96;83;14;88;34;89;63;72|];
      [|21;36;23;09;75;00;76;44;20;45;35;14;00;61;33;97;34;31;33;95|];
      [|78;17;53;28;22;75;31;67;15;94;03;80;04;62;16;14;09;53;56;92|];
      [|16;39;05;42;96;35;31;47;55;58;88;24;00;17;54;24;36;29;85;57|];
      [|86;56;00;48;35;71;89;07;05;44;44;37;44;60;21;58;51;54;17;58|];
      [|19;80;81;68;05;94;47;69;28;73;92;13;86;52;17;77;04;89;55;40|];
      [|04;52;08;83;97;35;99;16;07;97;57;32;16;26;26;79;33;27;98;66|];
      [|88;36;68;87;57;62;20;72;03;46;33;67;46;55;12;32;63;93;53;69|];
      [|04;42;16;73;38;25;39;11;24;94;72;18;08;46;29;32;40;62;76;36|];
      [|20;69;36;41;72;30;23;88;34;62;99;69;82;67;59;85;74;04;36;16|];
      [|20;73;35;29;78;31;90;01;74;31;49;71;48;86;81;16;23;57;05;54|];
      [|01;70;54;71;83;51;54;69;16;92;33;48;61;43;52;01;89;19;67;48|];
      |]

let dimensions = (Array2D.length1 numbers, Array2D.length2 numbers)

let horizontal_traverser (i, j) (iMax, jMax) f_4 =
    if (i &gt; iMax) || (j + 4&gt; jMax) then 0
    else f_4 numbers.[i,j]  numbers.[i, j+1] numbers.[i,j+2] numbers.[i,j+3]

let vertical_traverser (i,j) (iMax, jMax) f_4 =
    if (i + 4 &gt; iMax) || (j &gt; jMax) then 0
    else f_4 numbers.[i,j] numbers.[i+1, j] numbers.[i+2, j] numbers.[i+3,j]

let diagonal_traverser_left_right (i, j) (iMax, jMax) f_4 =
    if (i + 4 &gt; iMax) || (j + 4 &gt; jMax) then 0
    else f_4 numbers.[i,j] numbers.[i+1, j+1] numbers.[i+2, j+2] numbers.[i+3,j+3]

let diagonal_traverser_right_left (i, j) (iMax, jMax) f_4 =
    if (i - 3 &lt; 0) || (j + 4 &gt; jMax) then 0
    else f_4 numbers.[i,j] numbers.[i-1, j+1] numbers.[i-2, j+2] numbers.[i-3,j+3]

let max_in_direction traverser f_4 =
    seq { for i in 0..fst dimensions - 1 do
              for j in 0..snd dimensions - 1 do
                  yield traverser (i,j) dimensions f_4 }
    |&gt; Seq.max

let maximum f_4 =
    [| max_in_direction horizontal_traverser f_4;
       max_in_direction vertical_traverser f_4;
       max_in_direction diagonal_traverser_left_right f_4;
       max_in_direction diagonal_traverser_right_left f_4 |]
    |&gt; Array.max

let problem_11 () =
    maximum (fun a b c d -&gt; a * b * c * d)
</pre>
<ul>
<li>We first declare a two-dimensions array containing the 20&#215;20 numbers that we need to explore. To do this we use F# <a href="http://msdn.microsoft.com/en-us/library/ee353794.aspx">Array2D Module</a>. The same module is used also to compute a tuple containing the size of the two dimension arrays, which we&#39;ll use later on.</li>
<li>We then proceed to define four <i>traverser</i> functions, one for each of these directions: horizontal, vertical, diagonal top-left to bottom-right and diagonal bottom-left to top-right. Each traverser takes as input a given item of the array and applies the supplied 4-parameters function to the starting item plus the next 3 items in a direction. Note how at this point we are not talking about a specific operation (product or sum) yet and we are concentrating on 4 items of the array at a time.</li>
<li>Next we define the <code>max_in_direction</code> function that takes a traverser and a 4-parameters function and finds the maximum value in that particular direction (whatever it might be applying the given function).</li>
<li>We are getting closer to the solution by defining the <code>maximum</code> one-dimension array, where each item is the maximum value in each of the four directions and then taking the highest one.</li>
<li>We finally solve the problem by invoking the <code>maximum</code> function passing to it the product of four items as a lambda.</li>
</ul>
<p>Note how easy it is to change the particular function that we use to aggregate the 4 items: suppose for example that we are interested in the 4 items giving the maximum <i>sum</i>, we could simply invoke:</p>
<pre class="brush:csharp">maximum (fun a b c d -&gt; a + b + c + d)
</pre>
<p>
<a href="../../tag/euler-problems/" class="broken_link">See all Project Euler problems solutions</a>.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2010/09/21/project-euler-problem-11-in-f/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2010/09/21/project-euler-problem-11-in-f/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a href="http://dotnetshoutout.com/Project-Euler-Problem-11-in-F-Stefano-Ricciardi" rev="vote-for"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F09%2F21%2Fproject-euler-problem-11-in-f%2F" style="border: 0px none;" /></a></p>

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

