数组c#中数字的组合/排列

时间:2014-08-02 20:39:01

标签: 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=4 => {{1,2,3,4}}

其中source是源数组,count是排列长度。 我需要编写一个具有以下规范的方法:

public static IEnumerable<T[]> GenerateAllPermutations<T>(T[] source, int count)
{}

我使用以下方法来获取所有排列:

static IEnumerable<IEnumerable<T>> 
    GetKCombs<T>(IEnumerable<T> list, int length) where T : IComparable
{
    if (length == 1) return list.Select(t => new T[] { t });
    return GetKCombs(list, length - 1)
        .SelectMany(t => list.Where(o => o.CompareTo(t.Last()) > 0), 
            (t1, t2) => t1.Concat(new T[] { t2 }));
} 

此输出为({1, 2, 3, 4}列表和2的长度

{1,2} {1,3} {1,4} {2,3} {2,4} {3,4}

所以问题是:如何通过正确的类型转换调用GetKCombs方法中的GenerateAllPermutations方法?

非常感谢你!

1 个答案:

答案 0 :(得分:1)

同样将IComparable约束应用于排列方法的泛型参数,然后像这样调用它:

public static IEnumerable<T[]> GenerateAllPermutations<T>(
        T[] source,
        int count)
        where T : IComparable
{
     return GetKCombs(source, count).Select(x => x.ToArray());
}