<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>Felice Pollano Blog - Programmin</title>
    <link>http://www.felicepollano.com/</link>
    <description>The official Fatica Labs Blog!</description>
    <language>en-us</language>
    <copyright>Felice Pollano</copyright>
    <lastBuildDate>Wed, 29 Feb 2012 21:47:36 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.3.9074.18820</generator>
    <managingEditor>felice@felicepollano.com</managingEditor>
    <webMaster>felice@felicepollano.com</webMaster>
    <item>
      <trackback:ping>http://www.felicepollano.com/Trackback.aspx?guid=ceb5a0ad-03d4-48e8-81fa-865a8b3e65d2</trackback:ping>
      <pingback:server>http://www.felicepollano.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.felicepollano.com/PermaLink.aspx?guid=ceb5a0ad-03d4-48e8-81fa-865a8b3e65d2</pingback:target>
      <dc:creator>Felice Pollano</dc:creator>
      <wfw:comment>http://www.felicepollano.com/CommentView.aspx?guid=ceb5a0ad-03d4-48e8-81fa-865a8b3e65d2</wfw:comment>
      <wfw:commentRss>http://www.felicepollano.com/SyndicationService.asmx/GetEntryCommentsRss?guid=ceb5a0ad-03d4-48e8-81fa-865a8b3e65d2</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
In this post I will show how to make testable something that ( at least me ) usually
left as untested. I’m talking about the preparing phase of a console app, the checking
arguments error reporting and so on. That logic is usually so simple that any good
cow boy programmer would probably leave outside any unit testing. Unfortunately we
should at least do some manually check that prove that logic working, and doing things
manually is always silly. In this post we assume we have a <a href="http://www.ndesk.org/Options" target="_blank">working
command line parsing library</a>, <a href="http://code.google.com/p/moq/" target="_blank">and
a mocking framework</a>. Let see the cowboy code:
</p>
        <pre lang="C#">        static void Main(string[] args)
        {
            string optA,optB;
            optA = optB = null;
            bool done = false;
            OptionSet set = new OptionSet();
            set.Add("a=", (k) =&gt; optA = k);
            set.Add("b=", (k) =&gt; optB = k);
            set.Add("h", (k) =&gt; { LongHelp(); done = true; });
            set.Parse(args);
            if (done)
                return;
            if (string.IsNullOrEmpty(optA) || string.IsNullOrEmpty(optB))
            {
                ShortHelp();
                return;
            }
            DoTheJob(optA,optB);
            
        }

        private static void DoTheJob(string optA, string optB)
        {
            //something interesting here
        }

        private static void LongHelp()
        {
            Console.Error.WriteLine("Long help here...");
        }

        private static void ShortHelp()
        {
            Console.Error.WriteLine("Short help here");
        }
    }
</pre>
        <p>
So nothing special, the example is actually very simple, we have two mandatory parameters,
a command line switch to print a long help. If one argument is missing a short help
line must be presented. If all the parameters are provided, the DoTheJob() method
should be called with the correct values. 
</p>
        <p>
Current code is not testable without hosting the console application as a process,
and looking at the stdout to see what happen. Even by this strategy, we can not punctually
check what is passed to DoTheJob. So we want to refactor the code, without adding
any complexity to the app. So here below the proposed refactoring:
</p>
        <pre lang="C#">    public class Program
    {
        static void Main(string[] args)
        {
            new Program().Run(args);
        }
        public virtual void Run(string[] args)
        {
            string optA, optB;
            optA = optB = null;
            bool done = false;
            OptionSet set = new OptionSet();
            set.Add("a=", (k) =&gt; optA = k);
            set.Add("b=", (k) =&gt; optB = k);
            set.Add("h", (k) =&gt; { LongHelp(); done = true; });
            set.Parse(args);
            if (done)
                return;
            if (string.IsNullOrEmpty(optA) || string.IsNullOrEmpty(optB))
            {
                ShortHelp();
                return;
            }
            DoTheJob(optA, optB);

        }

        public virtual void DoTheJob(string optA, string optB)
        {
            //something interesting here
        }

        public virtual void LongHelp()
        {
            Console.Error.WriteLine("Long help here...");
        }

        public virtual void ShortHelp()
        {
            Console.Error.WriteLine("Short help here");
        }
    }
</pre>
        <p>
 
</p>
        <p>
So pretty easy, we provide a non static method Run(), and all the internal function
are declared virtual. This is a five minutes modification we could probably apply
to any other code like this we have. The difference is that we can write some unit
test, lets see how:
</p>
        <pre lang="C#">        [TestMethod]
        public void ShouldDisplayShortHelp()
        {
            var moq = new Mock<program>
(); moq.CallBase = true; moq.Setup(k=&gt;k.DoTheJob(It.IsAny<string>
(),It.IsAny<string>
())) .Throws(new InvalidProgramException("Should not call")); moq.Object.Run(new string[0]);
moq.Verify(k =&gt; k.ShortHelp()); } [TestMethod] public void ShouldDisplayLongHelp()
{ var moq = new Mock<program>
(); moq.CallBase = true; moq.Setup(k =&gt; k.DoTheJob(It.IsAny<string>
(), It.IsAny<string>
())) .Throws(new InvalidProgramException("Should not call")); moq.Object.Run(new string[]{"-h"});
moq.Verify(k =&gt; k.LongHelp()); } [TestMethod] public void ShouldInvokeWithProperParameters()
{ var moq = new Mock<program>
(); moq.CallBase = true; moq.Setup(k =&gt; k.DoTheJob("p1", "p2")).Verifiable(); moq.Object.Run(new
string[] { "-a=p1","-b=p2" }); moq.Verify(); } 
</program></string></string></program></string></string></program></pre>
        <p>
 
</p>
        <p>
I used the MoQ library, please note the Callbase set to true, because we are using
the same object for driving and for expect calls. So in conclusion, we achieve a real
unit test of something we sometimes left apart, we did that in memory, and even if
the example is really trivial, the concept can be used in complex scenarios too. What
about testing the inside part of DoTheJob()? well, if a good testing strategy is used,
the internal part should be testable outside somewhere else, here we are  proving
we can test the shell.  
</p>
        <img width="0" height="0" src="http://www.felicepollano.com/aggbug.ashx?id=ceb5a0ad-03d4-48e8-81fa-865a8b3e65d2" />
      </body>
      <title>From Untestable to Testable Console App</title>
      <guid isPermaLink="false">http://www.felicepollano.com/PermaLink.aspx?guid=ceb5a0ad-03d4-48e8-81fa-865a8b3e65d2</guid>
      <link>http://www.felicepollano.com/2012/02/29/FromUntestableToTestableConsoleApp.aspx</link>
      <pubDate>Wed, 29 Feb 2012 21:47:36 GMT</pubDate>
      <description>&lt;p&gt;
In this post I will show how to make testable something that ( at least me ) usually
left as untested. I’m talking about the preparing phase of a console app, the checking
arguments error reporting and so on. That logic is usually so simple that any good
cow boy programmer would probably leave outside any unit testing. Unfortunately we
should at least do some manually check that prove that logic working, and doing things
manually is always silly. In this post we assume we have a &lt;a href="http://www.ndesk.org/Options" target="_blank"&gt;working
command line parsing library&lt;/a&gt;, &lt;a href="http://code.google.com/p/moq/" target="_blank"&gt;and
a mocking framework&lt;/a&gt;. Let see the cowboy code:
&lt;/p&gt;
&lt;pre lang="C#"&gt;        static void Main(string[] args)
        {
            string optA,optB;
            optA = optB = null;
            bool done = false;
            OptionSet set = new OptionSet();
            set.Add("a=", (k) =&amp;gt; optA = k);
            set.Add("b=", (k) =&amp;gt; optB = k);
            set.Add("h", (k) =&amp;gt; { LongHelp(); done = true; });
            set.Parse(args);
            if (done)
                return;
            if (string.IsNullOrEmpty(optA) || string.IsNullOrEmpty(optB))
            {
                ShortHelp();
                return;
            }
            DoTheJob(optA,optB);
            
        }

        private static void DoTheJob(string optA, string optB)
        {
            //something interesting here
        }

        private static void LongHelp()
        {
            Console.Error.WriteLine("Long help here...");
        }

        private static void ShortHelp()
        {
            Console.Error.WriteLine("Short help here");
        }
    }
&lt;/pre&gt;
&lt;p&gt;
So nothing special, the example is actually very simple, we have two mandatory parameters,
a command line switch to print a long help. If one argument is missing a short help
line must be presented. If all the parameters are provided, the DoTheJob() method
should be called with the correct values. 
&lt;/p&gt;
&lt;p&gt;
Current code is not testable without hosting the console application as a process,
and looking at the stdout to see what happen. Even by this strategy, we can not punctually
check what is passed to DoTheJob. So we want to refactor the code, without adding
any complexity to the app. So here below the proposed refactoring:
&lt;/p&gt;
&lt;pre lang="C#"&gt;    public class Program
    {
        static void Main(string[] args)
        {
            new Program().Run(args);
        }
        public virtual void Run(string[] args)
        {
            string optA, optB;
            optA = optB = null;
            bool done = false;
            OptionSet set = new OptionSet();
            set.Add("a=", (k) =&amp;gt; optA = k);
            set.Add("b=", (k) =&amp;gt; optB = k);
            set.Add("h", (k) =&amp;gt; { LongHelp(); done = true; });
            set.Parse(args);
            if (done)
                return;
            if (string.IsNullOrEmpty(optA) || string.IsNullOrEmpty(optB))
            {
                ShortHelp();
                return;
            }
            DoTheJob(optA, optB);

        }

        public virtual void DoTheJob(string optA, string optB)
        {
            //something interesting here
        }

        public virtual void LongHelp()
        {
            Console.Error.WriteLine("Long help here...");
        }

        public virtual void ShortHelp()
        {
            Console.Error.WriteLine("Short help here");
        }
    }
&lt;/pre&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
So pretty easy, we provide a non static method Run(), and all the internal function
are declared virtual. This is a five minutes modification we could probably apply
to any other code like this we have. The difference is that we can write some unit
test, lets see how:
&lt;/p&gt;
&lt;pre lang="C#"&gt;        [TestMethod]
        public void ShouldDisplayShortHelp()
        {
            var moq = new Mock&lt;program&gt;
(); moq.CallBase = true; moq.Setup(k=&amp;gt;k.DoTheJob(It.IsAny&lt;string&gt;
(),It.IsAny&lt;string&gt;
())) .Throws(new InvalidProgramException("Should not call")); moq.Object.Run(new string[0]);
moq.Verify(k =&amp;gt; k.ShortHelp()); } [TestMethod] public void ShouldDisplayLongHelp()
{ var moq = new Mock&lt;program&gt;
(); moq.CallBase = true; moq.Setup(k =&amp;gt; k.DoTheJob(It.IsAny&lt;string&gt;
(), It.IsAny&lt;string&gt;
())) .Throws(new InvalidProgramException("Should not call")); moq.Object.Run(new string[]{"-h"});
moq.Verify(k =&amp;gt; k.LongHelp()); } [TestMethod] public void ShouldInvokeWithProperParameters()
{ var moq = new Mock&lt;program&gt;
(); moq.CallBase = true; moq.Setup(k =&amp;gt; k.DoTheJob("p1", "p2")).Verifiable(); moq.Object.Run(new
string[] { "-a=p1","-b=p2" }); moq.Verify(); } 
&lt;/pre&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
I used the MoQ library, please note the Callbase set to true, because we are using
the same object for driving and for expect calls. So in conclusion, we achieve a real
unit test of something we sometimes left apart, we did that in memory, and even if
the example is really trivial, the concept can be used in complex scenarios too. What
about testing the inside part of DoTheJob()? well, if a good testing strategy is used,
the internal part should be testable outside somewhere else, here we are&amp;nbsp; proving
we can test the shell.&amp;nbsp; 
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.felicepollano.com/aggbug.ashx?id=ceb5a0ad-03d4-48e8-81fa-865a8b3e65d2" /&gt;</description>
      <comments>http://www.felicepollano.com/CommentView.aspx?guid=ceb5a0ad-03d4-48e8-81fa-865a8b3e65d2</comments>
      <category>CodeProject</category>
      <category>CSharp</category>
      <category>Programmin</category>
    </item>
    <item>
      <trackback:ping>http://www.felicepollano.com/Trackback.aspx?guid=3ebe01be-7d6d-4f7a-aa0b-8488e3d568eb</trackback:ping>
      <pingback:server>http://www.felicepollano.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.felicepollano.com/PermaLink.aspx?guid=3ebe01be-7d6d-4f7a-aa0b-8488e3d568eb</pingback:target>
      <dc:creator>Felice Pollano</dc:creator>
      <wfw:comment>http://www.felicepollano.com/CommentView.aspx?guid=3ebe01be-7d6d-4f7a-aa0b-8488e3d568eb</wfw:comment>
      <wfw:commentRss>http://www.felicepollano.com/SyndicationService.asmx/GetEntryCommentsRss?guid=3ebe01be-7d6d-4f7a-aa0b-8488e3d568eb</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
This is a post for myself, because I’m much more a <a href="http://c2.com/cgi/wiki?CowboyCoder" target="_blank">cow
boy programmer</a>, and I know this is bad, even if sometimes results are apparently
good. The leaking part in my code are usually unit tests, and there is no excuse about
that, since it is necessary to change the approach on its root, for example writing
the (failing) <a href="http://c2.com/cgi/wiki?CodeUnitTestFirst" target="_blank">test
before the real code</a>. This is actually a <em>design </em>strategy, that eventually
improve the reliability of the software and the portability of the software against
other developers. The hardest part is that sometimes the boundary between unit testing
and integration testing is apparently very thin: making that boundary better defined
is part of the design process. <a href="http://misko.hevery.com/attachments/Guide-Writing%20Testable%20Code.pdf" target="_blank">I
found this document</a>, and I think is very useful to understand the common errors
producing a non testable code, and the strategy to avoid them. 
</p>
        <img width="0" height="0" src="http://www.felicepollano.com/aggbug.ashx?id=3ebe01be-7d6d-4f7a-aa0b-8488e3d568eb" />
      </body>
      <title>Writing testable code</title>
      <guid isPermaLink="false">http://www.felicepollano.com/PermaLink.aspx?guid=3ebe01be-7d6d-4f7a-aa0b-8488e3d568eb</guid>
      <link>http://www.felicepollano.com/2012/02/28/WritingTestableCode.aspx</link>
      <pubDate>Tue, 28 Feb 2012 21:13:39 GMT</pubDate>
      <description>&lt;p&gt;
This is a post for myself, because I’m much more a &lt;a href="http://c2.com/cgi/wiki?CowboyCoder" target="_blank"&gt;cow
boy programmer&lt;/a&gt;, and I know this is bad, even if sometimes results are apparently
good. The leaking part in my code are usually unit tests, and there is no excuse about
that, since it is necessary to change the approach on its root, for example writing
the (failing) &lt;a href="http://c2.com/cgi/wiki?CodeUnitTestFirst" target="_blank"&gt;test
before the real code&lt;/a&gt;. This is actually a &lt;em&gt;design &lt;/em&gt;strategy, that eventually
improve the reliability of the software and the portability of the software against
other developers. The hardest part is that sometimes the boundary between unit testing
and integration testing is apparently very thin: making that boundary better defined
is part of the design process. &lt;a href="http://misko.hevery.com/attachments/Guide-Writing%20Testable%20Code.pdf" target="_blank"&gt;I
found this document&lt;/a&gt;, and I think is very useful to understand the common errors
producing a non testable code, and the strategy to avoid them. 
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.felicepollano.com/aggbug.ashx?id=3ebe01be-7d6d-4f7a-aa0b-8488e3d568eb" /&gt;</description>
      <comments>http://www.felicepollano.com/CommentView.aspx?guid=3ebe01be-7d6d-4f7a-aa0b-8488e3d568eb</comments>
      <category>CodeProject</category>
      <category>Programmin</category>
    </item>
    <item>
      <trackback:ping>http://www.felicepollano.com/Trackback.aspx?guid=c3c5a1eb-4817-4071-954e-8d39193277de</trackback:ping>
      <pingback:server>http://www.felicepollano.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.felicepollano.com/PermaLink.aspx?guid=c3c5a1eb-4817-4071-954e-8d39193277de</pingback:target>
      <dc:creator>Felice Pollano</dc:creator>
      <wfw:comment>http://www.felicepollano.com/CommentView.aspx?guid=c3c5a1eb-4817-4071-954e-8d39193277de</wfw:comment>
      <wfw:commentRss>http://www.felicepollano.com/SyndicationService.asmx/GetEntryCommentsRss?guid=c3c5a1eb-4817-4071-954e-8d39193277de</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Sometimes happens that we need to roll over all the combinations of elements in multiple
arrays. This operation is called Cartesian Product and is defined as:
</p>
        <p>
          <b>Definition (Cartesian product):</b> Let <b><i>A<sub>1</sub></i>, ..., <i>A</i><sub><i>n</i></sub></b> be <b><i>n</i></b> sets. 
</p>
        <p>
Then the set of all ordered <b><i>n</i></b>-tuples <b>&lt;<i>x<sub>1</sub></i>, ..., <i>x</i><sub><i>n</i></sub>&gt;
,</b> where <b><i>x<sub>i</sub></i><img align="middle" src="http://www.cs.odu.edu/%7Etoida/nerzic/level-a/symbols_sets/in.gif" width="14" height="24" /><i>A<sub>i</sub></i></b> for
all <b><i>i</i></b>, <b><i>1</i><img align="middle" src="http://www.cs.odu.edu/%7Etoida/nerzic/level-a/symbols_sets/leq.gif" width="14" height="24" /><i>i</i><img align="middle" src="http://www.cs.odu.edu/%7Etoida/nerzic/level-a/symbols_sets/leq.gif" width="14" height="24" /><i>n</i> ,</b></p>
        <p>
is called the <b>Cartesian product</b> of <b><i>A<sub>1</sub></i>, ..., <i>A</i><sub><i>n</i></sub>,</b> and
is denoted by <b><i>A<sub>1</sub></i><img border="0" align="middle" src="http://www.cs.odu.edu/%7Etoida/nerzic/level-a/symbols_sets/times.gif" width="20" height="28" /> ... <img border="0" align="middle" src="http://www.cs.odu.edu/%7Etoida/nerzic/level-a/symbols_sets/times.gif" width="20" height="28" /><i>A<sub>n</sub></i> .</b></p>
        <p>
Achieving this is possible <a href="http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx" target="_blank">by
some linq tricks</a>, or by an helper class I propose in this post. But just for clarify
let’s start from the example:
</p>
        <p>
We have three array as below:
</p>
        <pre> { "JUICY", "SWEET" }<br />
{ "GREEN", "YELLOW" }<br />
{ "APPLE", "BANANA", "MANGO" }</pre>
        <p>
we want to obtain all the possible tuples, ie:
</p>
        <p>
 
</p>
        <p>
          <a href="http://www.felicepollano.com/public/WindowsLiveWriter/HelperclassfortheCartesianproductofmoret_B2B4/image_2.png">
            <img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://www.felicepollano.com/public/WindowsLiveWriter/HelperclassfortheCartesianproductofmoret_B2B4/image_thumb.png" width="467" height="176" />
          </a>
        </p>
        <p>
This can be achieved by the following code ( helper class ):
</p>
        <pre class="code">
          <span style="color: blue">public class </span>
          <span style="color: #2b91af">CartesianProduct</span>&lt;T&gt;
{ <span style="color: blue">int</span>[] lengths; T[][] arrays; <span style="color: blue">public </span>CartesianProduct(<span style="color: blue">params </span>T[][]
arrays) { lengths = arrays.Select(k =&gt; k.Length).ToArray(); <span style="color: blue">if </span>(lengths.Any(l
=&gt; l == 0)) <span style="color: blue">throw new </span><span style="color: #2b91af">ArgumentException</span>(<span style="color: #a31515">"Zero
lenght array unhandled."</span>); <span style="color: blue">this</span>.arrays = arrays;
} <span style="color: blue">public </span><span style="color: #2b91af">IEnumerable</span>&lt;T[]&gt;
Get() { <span style="color: blue">int</span>[] walk = <span style="color: blue">new
int</span>[arrays.Length]; <span style="color: blue">int </span>x = 0; <span style="color: blue">yield
return </span>walk.Select(k =&gt; arrays[x++][k]).ToArray(); <span style="color: blue">while </span>(Next(walk))
{ x = 0; <span style="color: blue">yield return </span>walk.Select(k =&gt; arrays[x++][k]).ToArray();
} } <span style="color: blue">private bool </span>Next(<span style="color: blue">int</span>[]
walk) { <span style="color: blue">int </span>whoIncrement = 0; <span style="color: blue">while </span>(whoIncrement
&lt; walk.Length) { <span style="color: blue">if </span>(walk[whoIncrement] &lt; lengths[whoIncrement]
- 1) { walk[whoIncrement]++; <span style="color: blue">return true</span>; } <span style="color: blue">else </span>{
walk[whoIncrement] = 0; whoIncrement++; } } <span style="color: blue">return false</span>;
} } </pre>
        <a href="http://11011.net/software/vspaste">
        </a>
        <p>
 
</p>
        <p>
        </p>
        <p>
And, just for completeness, the example application:
</p>
        <p>
 
</p>
        <pre class="code">
          <span style="color: blue">static void </span>Main(<span style="color: blue">string</span>[]
args) { <span style="color: blue">var </span>cross = <span style="color: blue">new </span><span style="color: #2b91af">CartesianProduct</span>&lt;<span style="color: blue">string</span>&gt;( <span style="color: blue">new
string</span>[] { <span style="color: #a31515">"JUICY"</span>, <span style="color: #a31515">"SWEET" </span>}
, <span style="color: blue">new string</span>[] { <span style="color: #a31515">"GREEN"</span>, <span style="color: #a31515">"YELLOW" </span>}
, <span style="color: blue">new string</span>[] { <span style="color: #a31515">"APPLE"</span>, <span style="color: #a31515">"BANANA"</span>, <span style="color: #a31515">"MANGO" </span>}
); <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"========================================================="</span>); <span style="color: blue">foreach </span>(<span style="color: blue">var </span>item <span style="color: blue">in </span>cross.Get())
{ <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"{0}\t{1}\t{2}"</span>,
item[0], item[1], item[2]); } <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"========================================================="</span>);
} </pre>Really simple and clear to use in comparison with other linq based solution,
even when arrays are unknown at design time.<a href="http://11011.net/software/vspaste"></a><img width="0" height="0" src="http://www.felicepollano.com/aggbug.ashx?id=c3c5a1eb-4817-4071-954e-8d39193277de" /></body>
      <title>Helper class for the Cartesian product of more than two arrays</title>
      <guid isPermaLink="false">http://www.felicepollano.com/PermaLink.aspx?guid=c3c5a1eb-4817-4071-954e-8d39193277de</guid>
      <link>http://www.felicepollano.com/2011/08/12/HelperClassForTheCartesianProductOfMoreThanTwoArrays.aspx</link>
      <pubDate>Fri, 12 Aug 2011 10:46:46 GMT</pubDate>
      <description>&lt;p&gt;
Sometimes happens that we need to roll over all the combinations of elements in multiple
arrays. This operation is called Cartesian Product and is defined as:
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Definition (Cartesian product):&lt;/b&gt; Let &lt;b&gt;&lt;i&gt;A&lt;sub&gt;1&lt;/sub&gt;&lt;/i&gt;, ..., &lt;i&gt;A&lt;/i&gt;&lt;sub&gt;&lt;i&gt;n&lt;/i&gt;&lt;/sub&gt;&lt;/b&gt; be &lt;b&gt;&lt;i&gt;n&lt;/i&gt;&lt;/b&gt; sets. 
&lt;/p&gt;
&lt;p&gt;
Then the set of all ordered &lt;b&gt;&lt;i&gt;n&lt;/i&gt;&lt;/b&gt;-tuples &lt;b&gt;&amp;lt;&lt;i&gt;x&lt;sub&gt;1&lt;/sub&gt;&lt;/i&gt;, ..., &lt;i&gt;x&lt;/i&gt;&lt;sub&gt;&lt;i&gt;n&lt;/i&gt;&lt;/sub&gt;&amp;gt;
,&lt;/b&gt; where &lt;b&gt;&lt;i&gt;x&lt;sub&gt;i&lt;/sub&gt;&lt;/i&gt; &lt;img align="middle" src="http://www.cs.odu.edu/%7Etoida/nerzic/level-a/symbols_sets/in.gif" width="14" height="24"&gt; &lt;i&gt;A&lt;sub&gt;i&lt;/sub&gt;&lt;/i&gt;&lt;/b&gt; for
all &lt;b&gt;&lt;i&gt;i&lt;/i&gt;&lt;/b&gt;, &lt;b&gt;&lt;i&gt;1&lt;/i&gt; &lt;img align="middle" src="http://www.cs.odu.edu/%7Etoida/nerzic/level-a/symbols_sets/leq.gif" width="14" height="24"&gt; &lt;i&gt;i&lt;/i&gt; &lt;img align="middle" src="http://www.cs.odu.edu/%7Etoida/nerzic/level-a/symbols_sets/leq.gif" width="14" height="24"&gt; &lt;i&gt;n&lt;/i&gt; ,&lt;/b&gt; 
&lt;/p&gt;
&lt;p&gt;
is called the &lt;b&gt;Cartesian product&lt;/b&gt; of &lt;b&gt;&lt;i&gt;A&lt;sub&gt;1&lt;/sub&gt;&lt;/i&gt;, ..., &lt;i&gt;A&lt;/i&gt;&lt;sub&gt;&lt;i&gt;n&lt;/i&gt;&lt;/sub&gt;,&lt;/b&gt; and
is denoted by &lt;b&gt;&lt;i&gt;A&lt;sub&gt;1&lt;/sub&gt;&lt;/i&gt; &lt;img border="0" align="middle" src="http://www.cs.odu.edu/%7Etoida/nerzic/level-a/symbols_sets/times.gif" width="20" height="28"&gt; ... &lt;img border="0" align="middle" src="http://www.cs.odu.edu/%7Etoida/nerzic/level-a/symbols_sets/times.gif" width="20" height="28"&gt; &lt;i&gt;A&lt;sub&gt;n&lt;/sub&gt;&lt;/i&gt; .&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Achieving this is possible &lt;a href="http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx" target="_blank"&gt;by
some linq tricks&lt;/a&gt;, or by an helper class I propose in this post. But just for clarify
let’s start from the example:
&lt;/p&gt;
&lt;p&gt;
We have three array as below:
&lt;/p&gt;
&lt;pre&gt; { "JUICY", "SWEET" }&lt;br&gt;
{ "GREEN", "YELLOW" }&lt;br&gt;
{ "APPLE", "BANANA", "MANGO" }&lt;/pre&gt;
&lt;p&gt;
we want to obtain all the possible tuples, ie:
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.felicepollano.com/public/WindowsLiveWriter/HelperclassfortheCartesianproductofmoret_B2B4/image_2.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://www.felicepollano.com/public/WindowsLiveWriter/HelperclassfortheCartesianproductofmoret_B2B4/image_thumb.png" width="467" height="176"&gt;&lt;/a&gt; 
&lt;/p&gt;
&lt;p&gt;
This can be achieved by the following code ( helper class ):
&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CartesianProduct&lt;/span&gt;&amp;lt;T&amp;gt;
{ &lt;span style="color: blue"&gt;int&lt;/span&gt;[] lengths; T[][] arrays; &lt;span style="color: blue"&gt;public &lt;/span&gt;CartesianProduct(&lt;span style="color: blue"&gt;params &lt;/span&gt;T[][]
arrays) { lengths = arrays.Select(k =&amp;gt; k.Length).ToArray(); &lt;span style="color: blue"&gt;if &lt;/span&gt;(lengths.Any(l
=&amp;gt; l == 0)) &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ArgumentException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;"Zero
lenght array unhandled."&lt;/span&gt;); &lt;span style="color: blue"&gt;this&lt;/span&gt;.arrays = arrays;
} &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;T[]&amp;gt;
Get() { &lt;span style="color: blue"&gt;int&lt;/span&gt;[] walk = &lt;span style="color: blue"&gt;new
int&lt;/span&gt;[arrays.Length]; &lt;span style="color: blue"&gt;int &lt;/span&gt;x = 0; &lt;span style="color: blue"&gt;yield
return &lt;/span&gt;walk.Select(k =&amp;gt; arrays[x++][k]).ToArray(); &lt;span style="color: blue"&gt;while &lt;/span&gt;(Next(walk))
{ x = 0; &lt;span style="color: blue"&gt;yield return &lt;/span&gt;walk.Select(k =&amp;gt; arrays[x++][k]).ToArray();
} } &lt;span style="color: blue"&gt;private bool &lt;/span&gt;Next(&lt;span style="color: blue"&gt;int&lt;/span&gt;[]
walk) { &lt;span style="color: blue"&gt;int &lt;/span&gt;whoIncrement = 0; &lt;span style="color: blue"&gt;while &lt;/span&gt;(whoIncrement
&amp;lt; walk.Length) { &lt;span style="color: blue"&gt;if &lt;/span&gt;(walk[whoIncrement] &amp;lt; lengths[whoIncrement]
- 1) { walk[whoIncrement]++; &lt;span style="color: blue"&gt;return true&lt;/span&gt;; } &lt;span style="color: blue"&gt;else &lt;/span&gt;{
walk[whoIncrement] = 0; whoIncrement++; } } &lt;span style="color: blue"&gt;return false&lt;/span&gt;;
} } &lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt; 
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
And, just for completeness, the example application:
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;Main(&lt;span style="color: blue"&gt;string&lt;/span&gt;[]
args) { &lt;span style="color: blue"&gt;var &lt;/span&gt;cross = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CartesianProduct&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;( &lt;span style="color: blue"&gt;new
string&lt;/span&gt;[] { &lt;span style="color: #a31515"&gt;"JUICY"&lt;/span&gt;, &lt;span style="color: #a31515"&gt;"SWEET" &lt;/span&gt;}
, &lt;span style="color: blue"&gt;new string&lt;/span&gt;[] { &lt;span style="color: #a31515"&gt;"GREEN"&lt;/span&gt;, &lt;span style="color: #a31515"&gt;"YELLOW" &lt;/span&gt;}
, &lt;span style="color: blue"&gt;new string&lt;/span&gt;[] { &lt;span style="color: #a31515"&gt;"APPLE"&lt;/span&gt;, &lt;span style="color: #a31515"&gt;"BANANA"&lt;/span&gt;, &lt;span style="color: #a31515"&gt;"MANGO" &lt;/span&gt;}
); &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;"========================================================="&lt;/span&gt;); &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;item &lt;span style="color: blue"&gt;in &lt;/span&gt;cross.Get())
{ &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;"{0}\t{1}\t{2}"&lt;/span&gt;,
item[0], item[1], item[2]); } &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;"========================================================="&lt;/span&gt;);
} &lt;/pre&gt;Really simple and clear to use in comparison with other linq based solution,
even when arrays are unknown at design time.&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;img width="0" height="0" src="http://www.felicepollano.com/aggbug.ashx?id=c3c5a1eb-4817-4071-954e-8d39193277de" /&gt;</description>
      <comments>http://www.felicepollano.com/CommentView.aspx?guid=c3c5a1eb-4817-4071-954e-8d39193277de</comments>
      <category>Programmin</category>
      <category>Recipes</category>
    </item>
  </channel>
</rss>