Last active
October 21, 2021 15:01
-
-
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
This file contains hidden or 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
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; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice. However can be shortened to: