C# 数组c中数字的组合/排列#
我需要得到一个具体长度的数组中的所有排列,例如C# 数组c中数字的组合/排列#,c#,arrays,algorithm,combinations,permutation,C#,Arrays,Algorithm,Combinations,Permutation,我需要得到一个具体长度的数组中的所有排列,例如 source = { 1,2,3,4 }, count=1 => {{1},{2},{3},{4}} source = { 1,2,3,4 }, count=2 => {{1,2},{1,3},{1,4},{2,3},{2,4},{3,4}} source = { 1,2,3,4 }, count=3 => {{1,2,3},{1,2,4},{1,3,4},{2,3,4}} source = { 1,2,3,4 }, count=
source = { 1,2,3,4 }, count=1 => {{1},{2},{3},{4}}
source = { 1,2,3,4 }, count=2 => {{1,2},{1,3},{1,4},{2,3},{2,4},{3,4}}
source = { 1,2,3,4 }, count=3 => {{1,2,3},{1,2,4},{1,3,4},{2,3,4}}
source = { 1,2,3,4 }, count=4 => {{1,2,3,4}}
其中source是源数组,count是置换长度。
我需要编写一个具有以下规范的方法:
public static IEnumerable<T[]> GenerateAllPermutations<T>(T[] source, int count)
{}
因此,问题是:如何调用GenerateAllPermutations
方法中的GetKCombs
方法来正确转换类型
多谢各位 将
IComparable
约束也应用于置换方法的泛型参数,然后像这样调用它:
public static IEnumerable<T[]> GenerateAllPermutations<T>(
T[] source,
int count)
where T : IComparable
{
return GetKCombs(source, count).Select(x => x.ToArray());
}
公共静态IEnumerable GeneratealPermutations(
T[]来源,
整数计数)
其中T:i可比较
{
返回GetKCombs(source,count);
}
您需要绕过这个IComparable约束吗?您可以使用索引(从原始数组)创建包装器结构,并将CompareTo重定向到该索引。也许您指的是组合,而不是置换。这似乎没问题!非常感谢。
{1,2} {1,3} {1,4} {2,3} {2,4} {3,4}
public static IEnumerable<T[]> GenerateAllPermutations<T>(
T[] source,
int count)
where T : IComparable
{
return GetKCombs(source, count).Select(x => x.ToArray());
}