2

我有多组数组,其中包含附加的数组,这些数组附加了用于计算数学的值。为了找到这些东西的最佳组合,我需要从这些数组中混合和匹配。我已经看到与此类似的“解决方案”,但它们通常是 1 个数组深,没有真正的组合/可能性。所以举个例子。

我有集合 A、B 和 C。集合 A 包含 Aa、Ab、Ac 和 Ad。Aa 包含一组值。为其他人推断出来。Aa 只能与 Ba 和 Ca 进行比较。如何编写一个程序来查找所有组合(即 Aa、Ab、Cc、Bd 与 Ba、Cb、Ac、Bd 等相比),以便我可以比较每个组合的数学以找到最佳组合?注意:这只是一个例子,具体3组4组4组不需要,需要能够扩展。

现在我知道我没有为我的变量使用非常有意义的名称,但是如果给出的任何代码中确实有有意义的名称,我将不胜感激(我真的不想在代码中围绕 x 和 c 的变量)。

4

2 回答 2

5

接受的答案似乎是正确的,但在 C# 中做笛卡尔积是一种非常奇怪的方式。如果您有给定数量的序列,您可以像这样惯用地采用他们的笛卡尔积:

    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));

如果您有任意多个序列需要获取他们的笛卡尔积,那么您可以这样做:

static class Extensions
{
  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})); 
  }
}

接着:

    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));

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

和我的回答

生成所有可能的组合

有关此问题的更多讨论。

于 2013-10-09T15:14:12.977 回答
-1

假设您使用的是支持 LINQ 的 C# 版本:

static void Main(string[] args)
    {
        // declare some lists
        var aList = new string[] { "a1", "a2", "a3" };
        var bList = new string[] { "b1", "b2", "b3" };
        var cList = new string[] { "c1", "c2", "c3" };

        // do the equivalent of a SQL CROSS JOIN
        var permutations = aList
            .Join(bList, a => "", b => "", (a, b) => new string[] { a, b })
            .Join(cList, ab => "", c => "", (ab, c) => new string[] { ab[0], ab[1], c });

        // print the results
        Console.WriteLine("Permutations:");
        foreach (var p in permutations)
            Console.WriteLine(string.Join(", ", p));
    }

使用 lambda 表达式将字符串指向空字符串的 Join 调用导致 Join 函数将字符串视为相等,模拟 SQL CROSS JOIN。

于 2013-10-09T01:32:48.203 回答