Skip to content

Instantly share code, notes, and snippets.

@mbenford
Last active October 21, 2021 15:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mbenford/95744f9d7c248eb976f6 to your computer and use it in GitHub Desktop.
Save mbenford/95744f9d7c248eb976f6 to your computer and use it in GitHub Desktop.
Generates all permutations of a set by using LINQ and a recursive approach
public static class Permutations
{
public static IEnumerable<IEnumerable<T>> Get<T>(IEnumerable<T> set, IEnumerable<T> subset = null)
{
if (subset == null) subset = new T[] { };
if (!set.Any()) yield return subset;
for (var i = 0; i < set.Count(); i++)
{
var newSubset = set.Take(i).Concat(set.Skip(i + 1));
foreach (var permutation in Get(newSubset, subset.Concat(set.Skip(i).Take(1))))
{
yield return permutation;
}
}
}
}
@PhilPJL
Copy link

PhilPJL commented Oct 21, 2021

Nice. However can be shortened to:

  public static IEnumerable<IEnumerable<T>> Get<T>(this IEnumerable<T> set, IEnumerable<T> subset = null)
  {
    subset = subset ?? Enumerable.Empty<T>();
		
    return set.Any()
      ? set.SelectMany((s,i) => Get(set.Take(i).Concat(set.Skip(i + 1)), subset.Concat(EnumerableEx.Return(s))))
      : EnumerableEx.Return(subset);
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment