我该如何获取一个由两个字符串组成的数组的组合?例如:
List<string> myString = {"a", "b", "c", "d", "f"};
一个排列看起来像这样:
ab
ac
ad
af
ba
bc
bd
bf
ca
cb
cd
cf
等等...
我不知道如何开始这个算法。如果有帮助的话,我宁愿使用循环而不是递归,因为在我的实际实现中,我必须为排列项分配一个值,并将每个项与另一个项进行比较并选择最高值。
我该如何获取一个由两个字符串组成的数组的组合?例如:
List<string> myString = {"a", "b", "c", "d", "f"};
一个排列看起来像这样:
ab
ac
ad
af
ba
bc
bd
bf
ca
cb
cd
cf
等等...
我不知道如何开始这个算法。如果有帮助的话,我宁愿使用循环而不是递归,因为在我的实际实现中,我必须为排列项分配一个值,并将每个项与另一个项进行比较并选择最高值。
使用Linq:
var result =
from a in myString
from b in myString
where a != b
select a + b;
不使用LINQ
List<string> myString = {"a", "b", "c", "d", "f"};
List<String> result = new List<String> ();
for (int i = 0; i < myString.Count; i++)
{
for (int j = 0; j < myString.Count; j++)
{
if (i == j)
continue;
result.Add(myString[i] + myString[j]);
}
}
for 循环
应该使用 j++
而不是 i++
。 - Alexandros B如果没有使用LINQ,你可以使用嵌套循环:
var permutations = new List<string>();
for(int i = 0; i < myString.Count; i++)
{
for(int j = 0; j < myString.Count; j++)
{
if(i == j)
continue;
var permutation = string.Format("{0}{1}", myString[i], myString[j]);
permutations.Add(permutation);
}
}
i < myString.Count - 1
,如果我没弄错的话,你会循环少一个元素,你需要使用 i <= myString.Count - 1
或者 i < myString.Count
。 - Alexandros B补充之前的回答:
string[] arreglo = new string[6];
arreglo[0] = "a";
arreglo[1] = "b";
arreglo[2] = "c";
arreglo[3] = "d";
arreglo[4] = "e";
arreglo[5] = "f";
var permutations = new List<string>();
for (int i = 0; i < arreglo.Length; i++)
{
for (int j = 0; j < arreglo.Length; j++)
{
for (int k = 0; k < arreglo.Length; k++)
{
for (int l = 0; l < arreglo.Length; l++)
{
for (int m = 0; m < arreglo.Length; m++)
{
for (int n = 0; n < arreglo.Length; n++)
{
if (i ==j ||j == k||i == k||k == l||i == l||j == l||i == m||j == m||k == m||l == m||i == n||j == n||k == n||l == n||m == n)
continue;
var permutation = string.Format("{0}{1}{2}{3}{4}{5}", arreglo[i], arreglo[j], arreglo[k], arreglo[l], arreglo[m],arreglo[n]);
permutations.Add(permutation);
}
}
}
}
}
}
foreach(var element in permutations)
{
Console.WriteLine(element);
}
Console.ReadLine();
List
,应该使用List<string> myString = new List<string> { "a", "b", "c", "d", "f" };
。 - nan