好的,這裏是我現在遇到的問題:我有一個元素列表,我想要使所有可能的組合成對。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);
}
謝謝。
埃裏克利珀有一系列有關排列,也許這將有助於:http://ericlippert.com/2013/04/15/producing-permutations-part-one/ – germi
http://www.codeproject.com/Articles/26050/Permutations-Combinations-and-Variations-using-CG –
使用此http://stackoverflow.com/questions/5128615/c-sharp-string-permutation – Oleh