2015-08-30 42 views
-3

我试过寻找,我没有找到我想要完成的东西。如何在两个组中找到List的所有组合?

比方说,我有一个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相同?

+0

你想要的结果只包含独特的集即使列表包含重复的值?或者:你知道该列表从不包含重复吗? – olydis

+0

@olydis如果你指的是我的源列表,源列表将永远不会有重复 –

+0

http://stackoverflow.com/questions/7802822/all-possible-combinations-of-a-list-of-values-in -c-sharp –

回答

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

for(int i = 0; i

+0

尝试'Console.WriteLine(string.Join(“,”,输出[i]));'而不是(循环很好,当然...) – olydis

+0

我讨厌打开另一个问题,但如果我有两个以上的哈希集创建,我怎样才能得到这两个集相同的组合? –

1
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)) 
     } 
    } 
} 
0

如果你只需要总组合则有一个公式

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' 
    } 
}