Skip to content

Instantly share code, notes, and snippets.

@Dynyx
Created June 4, 2012 13:34
Show Gist options
  • Save Dynyx/2868410 to your computer and use it in GitHub Desktop.
Save Dynyx/2868410 to your computer and use it in GitHub Desktop.
Permutation
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