【问题标题】:How to find all combinations of an List in sets of two?如何以两个为一组查找列表的所有组合?
【发布时间】:2015-08-30 20:06:38
【问题描述】:

我已经尝试过寻找,但没有找到太多我想要完成的事情。

假设我有一个List<int>,它有大约 50 个号码

List<int> _myList = new List<int>();
for (int i = 0; i < 49; i++)
{
    _myList.Add(i);
}

如何获得基于两个数组的组合列表?

例如 我的结果集看起来像

  1. 1,1
  2. 1,2
  3. 1,3
  4. 1,4
  5. 1,5

那些被认为是独一无二的。可以说1,22,1一样吗?

【问题讨论】:

  • 即使列表包含重复值,您是否希望结果仅包含唯一集?或者:您知道该列表从不包含重复项吗?
  • @olydis 如果你指的是我的源列表,源列表永远不会有重复
  • 使用 CodeProject 的 Adrian Akison 提供的出色的 Combinatorics 库。具体来说,您将使用 Combinations with Repetition 选项。我个人将这个库用于许多不同类型的项目。

标签: c# list combinations


【解决方案1】:

我假设您的源列表名为input

var output = new List<HashSet<int>>();
for (int i = 0; i < input.Count; i++)
    for (int j = i + 1; j < input.Count; j++)
        output.Add(new HashSet<int> { input[i], input[j] });

如果您想将结果实际输出到控制台:

foreach (var result in output)
    Console.WriteLine(string.Join(", ", result));

【讨论】:

  • for (int i = 0; i
  • 改用Console.WriteLine(string.Join(", ", output[i]));(循环很好,当然...)
  • 我不想再提出一个问题,但是如果我有上面您创建的两个哈希集,我如何才能获得这两个集的相同组合?
【解决方案2】:
var sets;

for (int i = 0; i < 49; i++)
{
   for (int j = 1; j < 49; j++)
   {
      if(setc.Contains(new Pair(_myList(i), _myList(j))==false)
      {
         sets.Add(new Pair(_myList(i), _myList(j))
      }
   }
}

【讨论】:

    【解决方案3】:

    如果您只需要总组合,那么有一个公式

    totalCombination = n!/(k! * (n-k)!)
    

    如果 n=50k=2

    我们可以将其解析为 50!/2!*48!

    但是以编程方式解决它

    for(int i=0;i<49;i++)
    {
        for(int j=i+1;j<=49;j++)
        {
            //Collect all the combinations in the form of 'i, j'
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多