【问题标题】:How to combine elements of a matrix without using the same row more than once each time如何组合矩阵的元素而不每次多次使用同一行
【发布时间】:2016-06-11 10:37:41
【问题描述】:

我的目标是组合这些元素(每个字母代表不同的字符串)

A;B;F;...
X;C;D;...
P;O;K;...
...

以各种可能的方式在文本框中,不重复也不组合同一行的元素。点代表延续。所以如果矩阵只是

A;B
X;C

结果应该是 AX AC BX BC。如果是

A;B;F
X;C;D
P;O;K

结果将是 AXP AXO AXK ACP ACO ACK ADP ADO ADK BXP ....

我找到了一个算法

private void buildAllCombinationsRecursive<TSource>(IList<TSource> i_targetList, IList<TSource> i_sourceList, int i_currentPos)
{
    if (i_currentPos == i_targetList.Count)
    {
        string combination = "";
        for (int i = 0; i < i_targetList.Count; i++)
        {
            combination += i_targetList[i] + " ";
        }

        Console.WriteLine(combination);
        return;
    }
    for (int i = 0; i < i_sourceList.Count; i++)
    {
        i_targetList[i_currentPos] = i_sourceList[i];
        this.buildAllCombinationsRecursive(i_targetList, i_sourceList, i_currentPos + 1);
    }
}

但它会创建一个我不需要的 ABC CBA 等。

【问题讨论】:

  • 该算法可以工作,要执行您要求的操作,您必须在删除使用的行后将第一次迭代中生成的源列表发送到目标列表,这样它就会执行相同的过程这次是第 2 行。
  • @DanielNetzer Kannst du das als Code darsellen?

标签: c# combinations permutation combinatorics


【解决方案1】:

查看 Eric Lippert 的 C# Cartesian product Recursion

你的每一行“矩阵”都是递归步骤中的一个序列。

累加器函数将是字符串连接。不过,出于性能考虑,您可以选择StringBuilder.Append

Example on rextester

【讨论】:

  • 请分享一个关于如何使用IEnumerable&lt;IEnumerable&lt;T&gt;&gt; CartesianProduct&lt;T&gt;(this IEnumerable&lt;IEnumerable&lt;T&gt;&gt; sequences) 解决我的问题的示例。
  • 我不认为这个网站的目的是提供完整的解决方案,而是想法。我编辑了答案。
  • 我确实认为这个网站的目的是提供完整的解决方案和想法。感谢您编辑答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-22
  • 1970-01-01
  • 2015-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多