Skip to content

Instantly share code, notes, and snippets.

@iAnatoly
Created June 11, 2015 22:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iAnatoly/883826b79d18ab13e72a to your computer and use it in GitHub Desktop.
Save iAnatoly/883826b79d18ab13e72a to your computer and use it in GitHub Desktop.
Generating permutations in C#
public static IEnumerable<IEnumerable<T>> GeneratePermutations<T>(IEnumerable<T> source)
{
var c = source.Count();
if (c == 1)
yield return source;
else
for (int i = 0; i < c; i++)
foreach (var shorter_permuttaion in GeneratePermutations<T>(source.Take(i).Concat(source.Skip(i + 1))))
yield return source.Skip(i).Take(1).Concat(shorter_permuttaion);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment