开发者

Generate all possible sequences from an Enumerable<int>

Given List {1,2,3,4,5}

I want to generate all possible sequences of those numbers in C#.

1,2,3,4,5 1,2,3,5,4 etc

It would be good if it was lazy evaluated, but it is not a necessity.

Should return

IEnumerable<IEnumerable<int>>

My intention is to wrap this into a custom LINQ op开发者_Python百科erator ("permutate" or something). But any good algorithm will be a good start.

Thank you.


try something like this:

    public static IEnumerable<List<T>> GetPermutations<T>(IEnumerable<T> items)
    {
        if (!items.Any()) 
            yield return new List<T>();
        foreach (var i in items)
        {
            var copy = new List<T>(items);
            copy.Remove(i);
            foreach(var rest in GetPermutations(copy))
            {
                rest.Insert(0, i);
                yield return rest;
            }
        }
    }

    public static IEnumerable<IEnumerable<T>>  GetEnumPermutations<T>(IEnumerable<T> items )
    {
        return GetPermutations(items);
    }

of course you can change the List-implementation in there but internaly I would stick to some collection because the remove is easier to handle (.Where is possible but not as readable or performant)


    List<int> li = new List<int> { 1, 2, 3, 4, 5 };
    var ff = from a in li
             join b in li on 1 equals 1
             join c in li on 1 equals 1
             join d in li on 1 equals 1
             join e in li on 1 equals 1
             where 
             a != b && b != c && c != d && d != e &&
             a != c && b != d && c != e &&
             a != d && b != e && 
             a != e 
             select new { a, b, c, d, e };
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜