2015-07-19 28 views
2

可能已经有一个答案了,我只是用错误的术语进行搜索。我很抱歉,如果是这样,并要求你指出我现有的答案,如果确实有一个。C#可以从列表中获得DISTINCT组合

我需要的是能够从列表中获取列表并生成所有可能的不同组合。我的意思是不同的是,相同的组合不应以不同的顺序出现。假设我有一个值为“One”,“Two”和“Three”的列表,那么我希望输出为=“One”,“Two”,“Three”,“One ,二”,‘三’,‘一二三’

我对没兴趣‘空白’的组合,我不希望返回多个订单相同的组合。我发现并试图为我工作的大部分代码都有一个主要缺陷,那就是它会返回包括“Two three”和“Three two”在内的所有可能性,这在我的情况中是错误的。

我目前一直在努力适应的代码是从另一个SO问题(All Possible Combinations of a list of Values),看起来像这样:

public void GetCombination(System.Collections.Generic.List<string> list) 
    { 
     Combinations = new List<string>(); 
     double count = System.Math.Pow(2, list.Count); 
     for (int i = 1; i <= count - 1; i++) 
     { 
      string str = Convert.ToString(i, 2).PadLeft(list.Count, '0'); 
      for (int j = 0; j < str.Length; j++) 
      { 
       if (str[j] == '1') 
       { 
        Combinations.Add(list[j]); 
       } 
      } 
      ///Combinations = found; 
     } 
    } 

可惜我是新手,当涉及到C#和我只是很诚实使用它,因为一个同事提到,它可能比我现在的PowerShell脚本更快,它可以完成我正在寻找的任务...但是需要很长时间才能完成。

在此先感谢您的建议!

+0

你从来没有问过一个问题,什么是您所遇到的问题。 –

+0

当前的代码不会返回正确的输出......问题是,如何才能找到使用C#的独特组合? – Ethan

回答

2

下面是使用the power sets answer马丁·史密斯的代码的实现中提到:

class Program { 
    static void Main(string[] args) { 
     // find all possible combinations of this list 
     var input = new [] {"One", "Two", "Three"}; 
     var output = FastPowerSet(input); 

     Print(output); 
     Console.ReadLine(); 
    } 

    static T[][] FastPowerSet<T>(T[] seq) { 
     var powerSet = new T[1 << seq.Length][]; 
     powerSet[0] = new T[0]; // starting only with empty set 
     for (var i = 0; i < seq.Length; i++) { 
      var cur = seq[i]; 
      var count = 1 << i; // doubling list each time 
      for (var j = 0; j < count; j++) { 
       var source = powerSet[j]; 
       var destination = powerSet[count + j] = new T[source.Length + 1]; 
       for (var q = 0; q < source.Length; q++) 
        destination[q] = source[q]; 
       destination[source.Length] = cur; 
      } 
     } 
     return powerSet; 
    } 

    static void Print<T>(T[][] seq) { 
     for (var i = 0; i < seq.Length; i++) { 
      var line = new StringBuilder(); 
      for (var j = 0; j < seq[i].Length; j++) { 
       line.AppendFormat("{0}, ", seq[i][j]); 
      } 
      Console.WriteLine(line); 
     } 
    } 
} 
+0

你摇滚,我认为这是完美的。非常感谢你! – Ethan

相关问题