Tuesday, 13 April 2010

C# Permutations (using Rx System.Interactive)

public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> xs)
    if (!xs.Any())
        return EnumerableEx.Return(Enumerable.Empty<T>());
        return from zs in Permutations(xs.Skip(1))
               from i in Enumerable.Range(0, zs.Count() + 1)
               select zs.Take(i).Concat(EnumerableEx.Return(xs.First())).Concat(zs.Skip(i));                  


Joe W. said...

At the minimum that first method should be:

using(var e = xs.GetEnumerator())
return !e.MoveNext();

in order to properly dispose the IEnumerator.

You can also rewrite it to be:

return !xs.Any();

holoed said...

Thank you.
I agree with that. Stupid mistake.