views:

69

answers:

2

is there any way i can Optimize this:

public static IEnumerable<IEnumerable<int>> GenerateCombinedPatterns
    (IEnumerable<IEnumerable<int>> patterns1,
     IEnumerable<IEnumerable<int>> patterns2)
{
    return patterns1
           .Join(patterns2, p1key => 1, p2key => 1, (p1, p2) => p1.Concat(p2))
           .Where(r => r.Sum() <= stockLen)
           .AsParallel()
        as IEnumerable<IEnumerable<int>>;
}
+1  A: 

No point in making the query parallel at the very end. Update: Jon was right, my initial solution was incorrect and turns out my corrected solution was essentially the same as his.

public static IEnumerable<IEnumerable<int>> GenerateCombinedPatterns
    (IEnumerable<IEnumerable<int>> patterns1,
     IEnumerable<IEnumerable<int>> patterns2)
{
    var parallel1 = patterns1.AsParallel();
    return parallel1.SelectMany(p1 => patterns2.Select(p2 => p1.Concat(p2)))
        .Where(r => r.Sum() <= stockLen);
}
Jeff M
I don't believe this does the same thing as the original.
Jon Skeet
Yeah I'm looking at that Join() and at second look, perhaps was a flattening instead which was my initial guess.
Jeff M
if I add.AsParallel then the application seems to take around 6 times the time it takes if its not used.
Sam
Thanks Jeff and Jon.My Original Code runs on a set of Inputs for 14 seconds. Trying out Jeff's code,hangs the application.
Sam
+2  A: 

If you're looking for every combination, use SelectMany instead, usually performed with multiple "from" clauses:

return from p1 in patterns1
       from p2 in patterns2
       let combination = p1.Concat(p2)
       where combination.Sum() <= stockLen
       select combination;

That's without any parallelism though... depending on the expected collections, I'd probably just parallelize at one level, e.g.

return from p1 in patterns1.AsParallel()
       from p2 in patterns2
       let combination = p1.Concat(p2)
       where combination.Sum() <= stockLen
       select combination;

Note that there's no guarantee as to the order in which the results come out with the above - you'd need to tweak it if you wanted the original ordering.

Jon Skeet