Posts Tagged cartesian products

LINQ Extension Method to Generate n-way Cartesian Product


Introduction

This blog post presents a LINQ extension method that implements the generation of Cartesian productfor any number of input sequences.

This implementation builds on the approach that I posted in LINQ Short Takes – Number 2 – Using Method Syntax to Create a Cartesian Product. Specifically, it uses the Enumerable Join Method to join the input IEnumerable sequences into the resulting Cartesian product.

Special Votes of Thanks and Referenced Articles:

Eric Lippert for Computing a Cartesian Product with LINQ, and
Ian Griffiths for LINQ and N-ary Cartesian Products

Whilst, the solution to the problem I present here is not the same as these articles present, these articles did push me down some of the correct paths. One thing that these articles helped me with was getting the ‘shape’ of the returned Cartesian product ‘right’ (correct by my judgement). The ‘shape’ I settled on was an IEnumerable, or a sequence of elements, each element being an IEnumerable with on element from each of the input IEnumerable objects.

The CartesianProduct Extension Method

In the following sections, I present the design, implementation, and some sample code, that describes the development process resulting in the CartesianProduct extension method.

CartesianProduct – Design Goals

There were numerous of design features that I wished to include in the implementation of CartesianProduct method. These features included:

  • The method must create a Cartesian product. This is a mandatory design criterion.
  • The order of the resulting Cartesian product elements must be in the same order as the input sequences. This may well be a defining attribute of a Cartesian product, but I include this characteristic as a design goal anyway. This is a mandatory design criterion.
  • The returned set of Cartesian product elements should be as generic as possible. This is a mandatory design criterion.
  • The returned set of Cartesian product elements should be easily processed using Linq. This is a mandatory design criterion.
  • The method’s implementation must be as an extension method. This is a mandatory design criterion.
  • The method’s implementation must be an extension method that operates like any other Linq extension method (see: IEnumerable(Of T) Interface). This allows the users of the extension method to chain it within a set of other calls to Linq extension methods calls. This allows the user to assemble Linq transformations that they require. This is a mandatory design criterion.
  • The method should accept, as generically as possible, the set of sequences that used to generate the Cartesian product. This is a mandatory design criterion.
  • The method should use the Linq Join extension method to build the Cartesian product. If had to resort to the Linq Aggregate extension method, then the two articles I have referenced above demonstrate that approach. Plagiarising those works, and representing there content here, was not an acceptable outcome. This was a highly desirable, leaning heavily to mandatory, design criterion.

CartesianProduct – Function Signature

The following is the function signature for the CartesianProduct extension method. Many features of the function signature directly address the design goals.

public static IEnumerable<IEnumerable<TSource>> CartesianProduct<TSource>
    (this IEnumerable<TSource> source,
    IEnumerable<IEnumerable<TSource>> inputs)
  • The return type IEnumerable<IEnumerable<TSource>> addresses the design goals for a generic return type, and a return type which can be processed with Linq. If it makes it easier to understand, you can interpret this type as an outer list of inner lists, each inner list being list made up of type the TSource objects. The following diagram attempts to show graphically what this ‘looks like’.

Figure 1 – IEnumerable of IEnumerable of T

Cartesian_Product_Output

 

  • The CartesianProduct<TSource> part of the method signature identifies this method as a parameterised type method (see MSDN article: Generic Methods (C# Programming Guide) for further information).declaration serves the design goal of requiring the method to accept as generically as possible inputs, and produce a generic output.
  • The argument this IEnumerable<TSource> source serves a couple of the design goals. Primarily, it flags this method as an extension method that should be attached, or associated, with any object that implements the IEnumerable(of T) Interface. Secondly, this argument identifies the first sequence used to assemble the Cartesian product.
  • The argument IEnumerable<IEnumerable<TSource>> inputs identifies the set of sequences to be processed to form the output Cartesian product. As with the return type, a loose interpretation is an outer list that contains inner list of objects. This satisfies the any number of input sequences design goal.

CartesianProduct – Implementation

The following is the implementation of the CartesianProduct extension method. I will detail many of the significant features after the source code.

public static IEnumerable<IEnumerable<TSource>> CartesianProduct<TSource>
    (this IEnumerable<TSource> source,
    IEnumerable<IEnumerable<TSource>> inputs)
{
    // Build the remaining work to be done var RemaimingJoinTarget = inputs.Skip(1);
    // Recursion end condition, no more to be done. if (RemaimingJoinTarget.Count( ) == 0)
    {
        // At the end of the inputs, return the Cartesian of two elements return source.Join(inputs.First( ),
            (outer) => 1, (inner) => 1,
            (outer, inner) =>
                ToIEnumerable(outer).UnionAll(ToIEnumerable(inner))
            //(new TSource[2] {outer, inner}).AsEnumerable<TSource>() );
    }
    else {
        // Recursive call down the list of inputs. // When coming back up add the source to the results already built. return source.Join(
            inputs.First( ).CartesianProduct(RemaimingJoinTarget),
            (outer) => 1, (inner) => 1,
            (outer, inner)
                => ToIEnumerable(outer).UnionAll(inner));
    }
}

The following are some of the significant features of the implementation:

  • Firstly, let me say that I find this implementation aesthetically pleasing. It is short, and concise, deceptively simple.
  • This implementation satisfies the design gaol of using the Linq Join extension method to form the Cartesian product.
  • This implementation satisfies the design gaol of does preserve of the order of the input sequences and reproduces that order in output Cartesian product.
  • This implementation satisfies the design gaol of being generic and catering for any input type. There are some nasty hoops the caller needs to jump through when mixing objects a with C# value types. Although, it may be nasty it does work. I have an example that shows what is required.
  • This is an implementation uses recursion, see the call to CartesianProduct in the Join contained in the else case. The version of recursion that is utilised here is tail recursion. The removal an element from the inputs parameter at each level of recursion controls the recursion. This technique of removing an element from a control sequence until nothing is left is an approach to controlling recursion I have used frequently.
  • There are two overloads of the helper function ToIEnumerable. These simply wrap an IEnumerable around the objects passed in. Using these functions allows the simple assembly of the result IEnumerable of objects with the Linq Union extension method.
  • The Cartesian product is formed within the Linq Join extension method. The same technique as described in LINQ Short Takes – Number 2 – Using Method Syntax to Create a Cartesian Product of setting the inner and outer join keys to 1.
  • The UnionAll LINQ extension method is described in LINQ Short Takes – Number 4 –Make Union into a UnionAll. The source code for the UnionAll extension method is in this blog post as well.

CartesianProduct – Helper Methods

There are two helper methods used in the implementation. These helper methods support the implementation of the CartesianProduct extension method. The source code for the helper methods is below.

public static IEnumerable<TSource> ToIEnumerable<TSource>(TSource val)
{
    yield return val;
}

And

public static IEnumerable<TSource> ToIEnumerable<TSource>(TSource val1, TSource val2)
{
    yield return val1;
    yield return val2;
}

There is one point worth noting about these methods. The implementation may not be the most efficient way to achieve the goal. The use of the yield return results in C# compiler implementing a ‘bunch of code’ under the covers. My justification for the implementation using yield return is simple. It results in very simple code for anyone who needs to maintain, or modify, the code.

CartesianProduct – Source Code

The following URL’s have the full source code, including XML Comments, for CartesianProduct and the two overloads of IEnumerable.
https://craigwatson1962.files.wordpress.com/2012/02/cartesianproduct-source-c-ode.docx
https://craigwatson1962.files.wordpress.com/2012/02/cartesianproduct-source-c-ode.pdf

Referenced LINQ Methods

The following are the Linq extension methods that are utilised in the implementation of the CartesianProduct extension method.

Join<(Of <<‘(TOuter, TInner, TKey, TResult>)>>)(IEnumerable<(Of <<‘(TOuter>)>>), IEnumerable<(Of <<‘(TInner>)>>), Func<(Of <<‘(TOuter, TKey>)>>), Func<(Of <<‘(TInner, TKey>)>>), Func<(Of <<‘(TOuter, TInner, TResult>)>>))

Skip<(Of <<‘(TSource>)>>)(IEnumerable<(Of <<‘(TSource>)>>), Int32)

Union<(Of <<‘(TSource>)>>)(IEnumerable<(Of <<‘(TSource>)>>), IEnumerable<(Of <<‘(TSource>)>>))

First<(Of <<‘(TSource>)>>)(IEnumerable<(Of <<‘(TSource>)>>))

CartesianProduct – Example Code

The following code assembles a range of different Cartesian products, and dumps them to the debug output window.

private void CartesianProducts_Extensions( )
{
    IEnumerable<int>[] SequsInt1 = new IEnumerable<int>[]
    {
        Enumerable.Range(0,5)
    };
    IEnumerable<int>[] SequsInt2 = new IEnumerable<int>[]
    {
        Enumerable.Range(0,5),
        Enumerable.Range(0,3)
    };
    IEnumerable<int>[] SequsInt3 = new IEnumerable<int>[]
    {
        Enumerable.Range(0,10),
        Enumerable.Range(0,5),
        Enumerable.Range(0,3)
    };
    //IEnumerable<IEnumerable<object>> ExpandedSequs1 = // LINQ_Extensions.ToIEnumerable(Enumerable.Range(0, 10).Cast<IEnumerable<object>>()); string[] SampleStrings = new string[]
    { "The", "quick", "red", "fox", "jumped",
        "over", "the", "lazy", "brown", "cow" };

    Action<IEnumerable<int>> IntDumper = (InnerSequence) =>
        {
            int column = 0;
            foreach (int innerVal in InnerSequence)
            {
                Debug.Write(string.Format("[{0}]={1}, ", column, innerVal));
                ++column;
            }
            Debug.WriteLine("");
        };

    var OuterInSource = Enumerable.Range(0, 10);
    var IntProd1 = Enumerable.Range(0, 10).CartesianProduct(SequsInt1);
    DumpCartesianProduct(IntProd1,
        (InnerSequence) =>
        {
            int column = 0;
            foreach (int innerVal in InnerSequence)
            {
                Debug.Write(string.Format("[{0}]={1}, ", column, innerVal));
                ++column;
            }
            Debug.WriteLine("");
        }
        );

    var IntProd1Vers2 = OuterInSource.CartesianProduct(SequsInt1);
    DumpCartesianProduct(IntProd1Vers2, IntDumper);

    var IntProd2 = Enumerable.Range(0, 10).CartesianProduct(SequsInt2);
    DumpCartesianProduct(IntProd2, IntDumper);

    var IntProd2Vers2 = OuterInSource.CartesianProduct(SequsInt2);
    DumpCartesianProduct(IntProd2Vers2, IntDumper);

    var IntProd3 = Enumerable.Range(0, 10).CartesianProduct(SequsInt3);
    DumpCartesianProduct(IntProd3, IntDumper);

    var IntProd3Vers2 = OuterInSource.CartesianProduct(SequsInt3);
    DumpCartesianProduct(IntProd3Vers2, IntDumper);

    // <IEnumerable<object>> Action<IEnumerable<object>> objDumper = (InnerSequence) =>
    {
        int column = 0;
        foreach (object innerVal in InnerSequence)
        {
            Debug.Write(string.Format("[{0}]={1}, ", column, innerVal));
            ++column;
        }
        Debug.WriteLine("");
    };
    var objStrings = SampleStrings.Cast<object>( );
    var objTransSequs1 = SequsInt1.ToList( ).Select(a => a.Select(b => (object) b));
    var MixedObjectProduct = objStrings.CartesianProduct(objTransSequs1);
    DumpCartesianProduct<object>(MixedObjectProduct, objDumper);

    var MixedObjectProduct2 = SampleStrings.CartesianProduct(objTransSequs1);
    DumpCartesianProduct<object>(MixedObjectProduct2, objDumper);

    IEnumerable<IEnumerable<object>> MixedSource =
        new IEnumerable<object>[]
        {
            from intVal in Enumerable.Range(0,5) select (object) intVal,
            from intVal in Enumerable.Range(0,5) select (object) new DateTime(2012, 1, 1).AddDays(intVal)
        };
    var MixedObjectProduct3 = SampleStrings.CartesianProduct(MixedSource);
    DumpCartesianProduct<object>(MixedObjectProduct3, objDumper);

    return;
}

private void DumpCartesianProduct<TSource>(
    IEnumerable<IEnumerable<TSource>> ResultSequence,
    Action<IEnumerable<TSource>> DumpLogic = null)
{
    if (DumpLogic != null)
    {
        foreach (IEnumerable<TSource> outputSeq in ResultSequence)
        {
            DumpLogic(outputSeq);
        }

    }
    return;
}

Possible Changes, Enhancements, Additional Overloads, Or Extra Features

I believe that additional versions of the CartesianProduct could be useful. These additional versions include:

· The creation of a variant of the Cartesian product method that accepts a variable number of arguments, as opposed to IEnumerable<IEnumerable<TSource> argument, could be useful.

Conclusion

For an implementation which started out as a ‘is it possible to do?’ question, the resulting implementation is quite effective and usable.

, , , , , , , , , , ,

1 Comment

LINQ Short Takes – Number 2 – Using Method Syntax to Create a Cartesian Product


Introduction

This is the second post in a series (I have no idea how many blog posts this series may comprise) of LINQ Short Takes. The first post was LINQ Short Takes – Number 1 – Enumerable.Range() which presented the Enumerable.Range() method. This blog post utilises the Enumerable.Range() method to form a Cartesian product utilising the LINQ method syntax (see: MSDN (Microsoft Developer Network Web Site) Article – LINQ Query Syntax versus Method Syntax (C#)for further discussion of the topic).

The motivation for developing this approach was twofold:

1. I did need a sequence of integers that formed a Cartesian product.

2. I experienced a degree of exasperation, frustration and downright ‘that’s wrong and very tacky’ when I looked for LINQ Cartesian Products using Method syntax. The solutions I read used a SelectMany()and lacked clarity that any good code should have.

So, I decided that there must be a simpler way to form a Cartesian product from two sequences using LINQ method calls. What has resulted is a solution to the problem that, in my opinion, is clear and concise. The solutions implementation uses a LINQ Join() method call to build the Cartesian product.

Cartesian Products

Please excuse the diversion into a little bit set theory. This diversion explains why the LINQ Join() method succeeds in forming a Cartesian product.

A Cartesian productis a resulting sequence of two input sequences. The output sequence has that all elements in the first sequence join with each element of the second sequence. The resulting sequence is series of element pairs from both input sequences. The length of the output sequence is the product of the lengths of the two input sequences.

The join operation between the two sequences that form the Cartesian producthas the following properties. If all of the elements in the two input sequences match each other, we have a type of join with a special property. This type of join’s special property implies that the join key for all of the elements in the two sequences is the same value.

Armed with the conclusion that a Cartesian product has the join key for both inputs sequences should be the same value. The process of forming a C# statement which utilises the Join() method to form a Cartesian product between the two input sequences becomes a simple process.

Example Code

The following C# method contains three examples of forming a Cartesian product. I will comment a little more on the three examples after the code.

The code also utilises the LINQ extension method ToOutput. This was the subject of a previous blog post: Dumping a formatted IEnumerable to Output.

I have loaded this code in Work docx and pfd formats as well. The URL’s are:
https://craigwatson1962.files.wordpress.com/2012/02/cartesianproducts.docx
https://craigwatson1962.files.wordpress.com/2012/02/cartesianproducts.pdf

private void CartesianProducts()
{
    // Query Syntax Cartesian Product var Prod1 = from num1 in Enumerable.Range(0, 10)
                from num2 in Enumerable.Range(0, 10)
                select new { num1, num2 };
    Debug.WriteLine("/nDump of Prod1");
    // Dump the contents of Prod1 Prod1.ToOutput(FormatFunction:
        (objValue, Position) =>
        {
            return string.Format("[{0}] {1},{2}\n",
                Position, objValue.num1, objValue.num2);
        });

    // Generate a Cartesian product using LINQ method syntax from two sequences var Prod2 = Enumerable.Range(0, 10).Join(Enumerable.Range(0,10),
        (iVal1) => 1, // Key selectors make all elements in first sequence (iVal2) => 1, // match all elements in the second sequence. (iVal1, iVal2) =>
            new {iVal1, iVal2}); // Create an object with the two values. Debug.WriteLine("/nDump of Prod2");
    // Dump the contents of Prod2 Prod2.ToOutput(FormatFunction:
        (objValue, Position) =>
        {
            return string.Format("[{0}] {1},{2}\n",
                Position, objValue.iVal1, objValue.iVal2);
        });

    string[] SampleStrings = new string[]
    { "The", "quick", "red", "fox", "jumped",
        "over", "the", "lazy", "brown", "cow" };
    // Generate a 3 way Cartesian product var Prod3 = Enumerable.Range(0, 10)
                    .Join(Enumerable.Range(0, 5), iVal1 => 1, iVal2 => 1,
                        (iVal1, iVal2) => new { iVal1, iVal2 })
                    .Join(SampleStrings, iVals => 1, strVals => 1,
                        (iVals, strVal) =>
                            new {
                                intValue1 = iVals.iVal1,
                                intValue2 = iVals.iVal2,
                                strValue = strVal });
    Debug.WriteLine("/nDump of Prod3");
    // Dump the contents of Prod3 Prod3.ToOutput(FormatFunction:
        (objVal, Position) =>
            string.Format("[0] {1},{2},'{3}'\n",
                Position, objVal.intValue1, objVal.intValue2, objVal.strValue));
    Debug.WriteLine(string.Format(
        "Double Check\n\tSequence1 Length {0} Sequence2 Length {1}" +
        "SampleStrings Length{2}\n\t" +
        "Input Sequence Product Value {3} Result Length {4}",
        Enumerable.Range(0, 10).Count(),
        Enumerable.Range(0, 5).Count(),
        SampleStrings.Count(),
        Enumerable.Range(0, 10).Count()
            * Enumerable.Range(0, 5).Count()
            * SampleStrings.Count(),
        Prod3.Count()));

    return;
}

The examples of forming a Cartesian product with LINQ are:

  1. This example uses the LINQ query syntax to create a Cartesian product. It uses an unconstrained join between the two sequences. This is exactly how SQL operates when used to form a Cartesian product.
  2. The second example uses the LINQ method syntax to form a Cartesian product between two integer sequences. These sequences are generated using the Enumerable.Range () method. The Cartesian product is formed using the LINQ method Join(). The arguments to the overload of the Join() methods are: the second IEnumerable, the outer (first sequence) key selector, the inner (the second sequence) key selector, and the result selector. The key selectors in each part of the join are just 1, which ‘says’ this is the join key for each of the same sequences.
  3. The third example demonstrates the scalability of the approach, by joining three sequences in a Cartesian product. If you can do this with two, and three sequences, then I would expect the approach would work with as many sequences as you require. This example also demonstrates the joining of different types of object using this approach.

If you missed it above, this example method also uses the ToOutput LINQ extension method. The ToOutput extension method was the subject of a previous blog post: Dumping a formatted IEnumerable to Output, and the code for the extension method is included there.

Conclusions

  • I believe that the approach presented is a clear, clean, and concise, approach to generation of a Cartesian product using the LINQ method syntax.
  • I suspect that I will generalise this approach into another LINQ extension method. The may well become another blog post. There are a couple of interesting deign decisions which I need to make when designing and implementing this approach as an extension method. I will leave those discussions for that blog post.

, , , , , , , ,

3 Comments

%d bloggers like this: