Ren*_*iko 1 c# arrays algorithm combinations
可能重复:
数组的不同组合(C#)
string[] array = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10"};
Run Code Online (Sandbox Code Playgroud)
如何生成每个组合2/3/4/5字符串,例如每个组合2个字符串,没有重复/重复,也忽略位置,使用组合公式nCr = 10!/ 2!(10-2)!= 45种组合.
我需要输出如下:
"01", "02"
"01", "03"
"01", "04"
...
"02", "03" // eliminate the "02","01" 'cause it is same as "01","02" combination
"02", "04"
...
Run Code Online (Sandbox Code Playgroud)
然后生成3个字符串的组合,将有120个组合(根据nCr).我需要输出如下:
"01","02","03"
"01","02","04"
...
Run Code Online (Sandbox Code Playgroud)
并且4个字符串的组合将具有210个组合,最少,每个组合5个字符串的组合将具有252个组合.
我该怎么写呢?我已经用完了许多循环,它看起来真的很乱.
小智 8
您可以使用简单的递归:
private static IEnumerable<string> Combinations(int start, int level)
{
for ( int i = start; i < array.Length; i++ )
if ( level == 1 )
yield return array[i];
else
foreach ( string combination in Combinations(i + 1, level - 1) )
yield return String.Format("{0} {1}", array[i], combination);
}
Run Code Online (Sandbox Code Playgroud)
这样称呼:
var combinations = Combinations(0, 2);
foreach ( var item in combinations )
Console.WriteLine(item);
Run Code Online (Sandbox Code Playgroud)
您可以使用此高效项目:使用C#Generics的排列,组合和变体.
string[] array = { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10" };
int lowerIndex = 2;
var combinations = new Facet.Combinatorics.Combinations<String>(
array,
lowerIndex,
Facet.Combinatorics.GenerateOption.WithoutRepetition
);
foreach (IList<String> combis in combinations)
{
String combi = String.Join(" ", combis);
Console.WriteLine(combi);
}
Run Code Online (Sandbox Code Playgroud)
由于它是开源的,你可以看看它是如何实现的.但上面的链接也非常有用.
输出(lowerIndex = 2):
01 02
01 03
01 04
01 05
01 06
01 07
01 08
01 09
01 10
02 03 <-- no 02 01 since it would be a repitition
02 04
02 05
// ... (45 combinations w/o repetitions)
09 10
Run Code Online (Sandbox Code Playgroud)
输出(lowerIndex = 5):
01 02 03 04 05
01 02 03 04 06
01 02 03 04 07
01 02 03 04 08
01 02 03 04 09
01 02 03 04 10
01 02 03 05 06
01 02 03 05 07
01 02 03 05 08
01 02 03 05 09
01 02 03 05 10
01 02 03 06 07
// ........... (252 combinations w/o repetitions)
05 07 08 09 10
06 07 08 09 10
Run Code Online (Sandbox Code Playgroud)