2013-11-21 15 views
1

好的,這裏是我現在遇到的問題:我有一個元素列表,我想要使所有可能的組合成對。C#在列表中的組合

例如:我有元素列表「A」,「B」,「C」,「E」。

出我要讓所有可能的組合對(沒有已經存在,而配對的元素重複元素)的元素,所以它會變成:

AB

AC

AE

BC

BE

CE

ABC

ABE

ACE

BCE

ABCE

到目前爲止,我的代碼不會使所有的組合就像上面的例子中,它似乎有重複的問題,我已經跑出了想法如何進一步處理這個問題。

List<char> charList = new List<char> { 'A', 'B', 'C', 'E' }; 
    List<string> copy = new List<string>(); 
    List<string> stringList = new List<string>(); 

    for (int i = 0; i < charList.Count() - 1; i++) 
    { 
     for (int j = i + 1; j < charList.Count(); j++) 
     { 
      stringList.Add(charList[i].ToString() + charList[j].ToString()); 
      copy = stringList.ToList(); 

     } 
    } 


    for (int i = 0; i < charList.Count() - 1; i++) 
    { 
     for (int j = i + 1; j < charList.Count(); j++) 
     { 
      for (int g = 0; g < stringList.Count(); g++) 
      { 

       if (!stringList[g].Contains(charList[i])) 
       { 
        stringList[g] += charList[i]; 
        copy.Add(stringList[g]); 
       } 
       else if (!stringList[g].Contains(charList[j])) 
       { 
        stringList[g] += charList[j]; 
        copy.Add(stringList[g]); 
       } 
      } 

     } 
    } 


    foreach (string value in copy) 
    { 
     Console.WriteLine(value); 
    } 

謝謝。

+0

埃裏克利珀有一系列有關排列,也許這將有助於:http://ericlippert.com/2013/04/15/producing-permutations-part-one/ – germi

+0

http://www.codeproject.com/Articles/26050/Permutations-Combinations-and-Variations-using-CG –

+0

使用此http://stackoverflow.com/questions/5128615/c-sharp-string-permutation – Oleh

回答

1
var charList = new List<char> { 'A', 'B', 'C', 'E' }; 
List<string> stringList = new List<string>(); 

for (var i = 1; i < Math.Pow(2, charList.Count); i++) 
{ 
    var sb = new StringBuilder(); 
    for (var j = 0; j < charList.Count; j++) 
    { 
     int power = (int)Math.Pow(2, j); 
     if ((i & power) == power) sb.Append(charList[j]); 
    } 
    var s = sb.ToString(); 
    if (s.Length > 1) stringList.Add(sb.ToString()); 
} 

// Sort results. 
stringList.Sort((s1, s2) => s1.Length != s2.Length 
    ? s1.Length.CompareTo(s2.Length) : s1.CompareTo(s2)); 
+0

(i&power == 1)的副本,這是如何工作的? –

+0

這對我來說不是一個錯誤。也許他更正((我&功率)== 1) –

+0

@ Djavier89,更正了我的答案,謝謝。 – Vladimir

0
namespace ConsoleApplication1 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     string[] list = new string[] { "A", "B", "C", "D" }; 
     List<string> combined = new List<string>(); 

     for (int i = 0; i < list.Length; i++) 
     { 
      combined.Add(list[i]); 
      for (int j = 0; j < list.Length; j++) 
      { 
       combined.Add(list[i] + list[j]); 
       for (int k = 0; k < list.Length; k++) 
       { 
        combined.Add(list[i] + list[j] + list[k]); 
        for (int l = 0; l < list.Length; l++) 
        { 
         combined.Add(list[i]+list[j] + list[k] + list[l]); 
        } 
       } 
      } 
     } 

     combined.ForEach(item => Console.WriteLine(item)); 

     Console.ReadKey(); 
    } 
} 

}