Created
March 20, 2014 13:28
-
-
Save forcewake/9663681 to your computer and use it in GitHub Desktop.
Permutations extension
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 EnumerableExtensions | |
| { | |
| public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> source) | |
| { | |
| if (source == null) | |
| throw new ArgumentNullException("source"); | |
| // Ensure that the source IEnumerable is evaluated only once | |
| return permutations(source.ToArray()); | |
| } | |
| private static IEnumerable<IEnumerable<T>> permutations<T>(IEnumerable<T> source) | |
| { | |
| var c = source.Count(); | |
| if (c == 1) | |
| yield return source; | |
| else | |
| for (int i = 0; i < c; i++) | |
| foreach (var p in permutations(source.Take(i).Concat(source.Skip(i + 1)))) | |
| yield return source.Skip(i).Take(1).Concat(p); | |
| } | |
| } | |
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 class Program | |
| { | |
| public static void Main() | |
| { | |
| List<string> list = new List<string> { "ОТ", "ТРПО", "НПО", "ЗН", "ПОВС" }; | |
| var perm = list.Permutations<string>().Where(enumerable => enumerable.Last() == "ПОВС").Where(enumerable => enumerable.First() == "ОТ"); | |
| foreach (var l in perm) | |
| { | |
| string s = string.Join(", ", l); | |
| Console.WriteLine(s); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment