Finding all combinations from sets of possibilities

前端 未结 2 923
伪装坚强ぢ
伪装坚强ぢ 2021-01-23 03:27

I have multiple sets of arrays that contain additional arrays that have values attached that I use for figuring out math. In order to find the best combination of these things,

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-23 03:49

    The accepted answer appears to be correct but is a very strange way to do a Cartesian product in C#. If you have a given number of sequences you can take their Cartesian product idiomatically like this:

        var aList = new[] { "a1", "a2", "a3" };
        var bList = new[] { "b1", "b2", "b3" };
        var cList = new[] { "c1", "c2", "c3" };
        var product = from a in aList
                      from b in bList
                      from c in cList
                      select new[] { a, b, c };
    
        foreach (var p in product)
            Console.WriteLine(string.Join(",", p));
    

    If you have arbitrarily many sequences that you need to take their Cartesian product then you can do it like this:

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

    And then:

        var aList = new[] { "a1", "a2", "a3" };
        var bList = new[] { "b1", "b2", "b3" };
        var cList = new[] { "c1", "c2", "c3" };
        var lists = new[] { aList, bList, cList };
        var product = lists.CartesianProduct();
        foreach (var p in product)
            Console.WriteLine(string.Join(",", p));
    

    See

    http://ericlippert.com/2010/06/28/computing-a-cartesian-product-with-linq/

    and my answer to

    Generating all Possible Combinations

    for more discussion of this problem.

提交回复
热议问题