Created
June 4, 2012 13:34
-
-
Save Dynyx/2868410 to your computer and use it in GitHub Desktop.
Permutation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace Permutation | |
{ | |
public static class Extension | |
{ | |
public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> source) | |
{ | |
if (source == null) | |
throw new ArgumentNullException("source"); | |
return PermutationsImpl(source, Enumerable.Empty<T>()); | |
} | |
private static IEnumerable<IEnumerable<T>> PermutationsImpl<T>(IEnumerable<T> source, IEnumerable<T> prefix) | |
{ | |
if (!source.Any()) | |
yield return prefix; | |
foreach (var permutation in source.SelectMany(x => PermutationsImpl(source.Except(Yield(x)), prefix.Union(Yield(x))))) | |
{ | |
yield return permutation; | |
} | |
} | |
private static IEnumerable<T> Yield<T>(this T element) | |
{ | |
yield return element; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment