Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var ps = "0123".Permute(3);
Console.WriteLine(string.Join(",", ps.Select(x => new string(x.ToArray()))));
}
}
public static class EnumerableEx
{
public static IEnumerable<IEnumerable<T>> Dist<T>(this IEnumerable<T> source, T element)
{
if (source.Any())
{
var head = source.First();
var tail = source.Skip(1);
yield return Enumerable.Repeat(element, 1).Concat(source);
foreach (var source2 in tail.Dist(element))
yield return Enumerable.Repeat(head, 1).Concat(source2);
}
else
{
yield return Enumerable.Repeat(element, 1);
}
}
public static IEnumerable<IEnumerable<T>> Permute<T>(this IEnumerable<T> source)
{
if (source.Any())
{
var head = source.First();
var tail = source.Skip(1);
foreach (var source2 in tail.Permute())
foreach (var source3 in source2.Dist(head))
yield return source3;
}
else
{
yield return Enumerable.Empty<T>();
}
}
public static IEnumerable<IEnumerable<T>> Permute<T>(this IEnumerable<T> source, int c)
{
if (c == 0)
{
yield return Enumerable.Empty<T>();
}
else if (source.Any())
{
var head = source.First();
var tail = source.Skip(1);
foreach (var source2 in tail.Permute(c))
yield return source2;
foreach (var source2 in tail.Permute(c - 1))
foreach (var source3 in source2.Dist(head))
yield return source3;
}
}
}