Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

c# - Cartesian Product + N x M Dynamic Array

I have looked hours for a solution without any success. Hopefully someone can help me out.

I have a dynamic array of N items on M origin zip codes.

For instance:

Item 1: 11001, 54010, 60621 Item 2: 11001, 60621 Item 3: 60621

I want to create a new array that will look like this:

Route 1: 11001, 11001, 60621 Route 2: 11001, 60621, 60621 Route 3: 54010, 11001, 60621

etc - until Route 6.

Suggestions?

---------------------- Is there any way to accomplish this WITHOUT using Linq? VB.net and Linq do not go together :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It sounds like you want this function from Eric Lippert's blog post written in response to Generating all Possible Combinations:

public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(
    this IEnumerable<IEnumerable<T>> sequences) 
{ 
    IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; 
    return sequences.Aggregate( 
        emptyProduct, 
        (accumulator, sequence) =>  
            from accseq in accumulator  
            from item in sequence  
            select accseq.Concat(new[] {item}));                
}

That would let you write code like this:

int[][] items = { 
                    new[] { 11001, 54010, 60621 },
                    new[] { 11001, 60621 },
                    new[] { 60621 }
                };
var routes = CartesianProduct(items);
foreach (var route in routes)
    Console.WriteLine(string.Join(", ", route));

And get output like this:

11001, 11001, 60621
11001, 60621, 60621
54010, 11001, 60621
54010, 60621, 60621
60621, 11001, 60621
60621, 60621, 60621

EDIT: Here's the VB.NET version (in VS2010)

Imports System.Runtime.CompilerServices

Module Module1
    <Extension()>
    Private Function CartesianProduct(Of T)(
            ByVal sequences As IEnumerable(Of IEnumerable(Of T))) _
            As IEnumerable(Of IEnumerable(Of T))
        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) =
            New IEnumerable(Of T)() {Enumerable.Empty(Of T)()}
        Return sequences.Aggregate(
            emptyProduct,
            Function(accumulator, sequence)
                Return (From accseq In accumulator
                        From item In sequence
                        Select accseq.Concat(New T() {item}))
            End Function)
    End Function

    Sub Main(ByVal args As String())
        Dim items = New Integer()() {New Integer() {11001, 54010, 60621},
                                     New Integer() {11001, 60621},
                                     New Integer() {60621}}
        Dim routes = items.CartesianProduct()
        Dim route As IEnumerable(Of Integer)
        For Each route In routes
            Console.WriteLine(String.Join(", ", route))
        Next
    End Sub
End Module

Of course, if you don't want any LINQ whatsoever, here's a completely LINQ-free recursive implementation:

public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(
    this IEnumerable<IEnumerable<T>> sequences)
{
    var accum = new List<T[]>();
    var list = sequences.ToList();
    if (list.Count > 0)
        CartesianRecurse(accum, new Stack<T>(), list, list.Count - 1);
    return accum;
}

static void CartesianRecurse<T>(List<T[]> accum, Stack<T> stack,
                                List<IEnumerable<T>> list, int index)
{
    foreach (T item in list[index])
    {
        stack.Push(item);
        if (index == 0)
            accum.Add(stack.ToArray());
        else
            CartesianRecurse(accum, stack, list, index - 1);
        stack.Pop();
    }
}

It doesn't return the items in the same order as the first function, but is otherwise functionally identical. If you don't like LINQ or recursion, here's a single LINQ-less method that does the same thing as the recursive version:

public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(
    this IEnumerable<IEnumerable<T>> sequences)
{
    var accum = new List<T[]>();
    var list = sequences.ToList();
    if (list.Count > 0)
    {
        var enumStack = new Stack<IEnumerator<T>>();
        var itemStack = new Stack<T>();
        int index = list.Count - 1;
        var enumerator = list[index].GetEnumerator();
        while (true)
            if (enumerator.MoveNext())
            {
                itemStack.Push(enumerator.Current);
                if (index == 0)
                {
                    accum.Add(itemStack.ToArray());
                    itemStack.Pop();
                }
                else
                {
                    enumStack.Push(enumerator);
                    enumerator = list[--index].GetEnumerator();
                }
            }
            else
            {
                if (++index == list.Count)
                    break;
                itemStack.Pop();
                enumerator = enumStack.Pop();
            }
    }
    return accum;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...