LINQ implementation of Cartesian Product with pruning

后端 未结 3 764
盖世英雄少女心
盖世英雄少女心 2021-01-22 03:23

I hope someone is able to help me with what is, at least to me, quite a tricky algorithm.

The Problem

I have a List (1 <= size <= 5, but siz

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-22 04:02

    The finalised solution to the whole combining of multisets, then pruning the result-sets to remove duplicates problem ended up in a helper class as a static method. It takes svick's much appreciated answer and injects the IEqualityComparer dependency into the existing CartesianProduct answer I found at Eric Lipperts's blog here (I'd recommend reading his post as it explains the iterations in his thinking and why the linq implimentation is the best).

    static IEnumerable> CartesianProduct(IEnumerable> sequences,
                                                           IEqualityComparer> sequenceComparer)
    {
        IEnumerable> emptyProduct = new[] { Enumerable.Empty() };
        var resultsSet = sequences.Aggregate(emptyProduct, (accumulator, sequence) => from accseq in accumulator
                                                                                      from item in sequence
                                                                                      select accseq.Concat(new[] { item }));
    
        if (sequenceComparer != null)
            return resultsSet.Distinct(sequenceComparer);
        else
            return resultsSet;
    }
    

提交回复
热议问题