Skip to content

Instantly share code, notes, and snippets.

@forcewake
Created March 20, 2014 13:28
Show Gist options
  • Select an option

  • Save forcewake/9663681 to your computer and use it in GitHub Desktop.

Select an option

Save forcewake/9663681 to your computer and use it in GitHub Desktop.
Permutations extension
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);
}
}
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