Permutate() is supposed to generate all possible permutations of the source sequence:
foreach(var s in "abc".Permutate())
Console.WriteLine(s); // abc
// acb
// bac
// bca
// cab
// cba
Where:
public static IEnumerable<string> Permutate(this string source) =>
source.AsEnumerable().Permutate().Select(a => new string(a));
public static IEnumerable<T[]> Permutate<T>(this IEnumerable<T> source)
{
return permutate(source, Enumerable.Empty<T>());
IEnumerable<T[]> permutate(IEnumerable<T> reminder, IEnumerable<T> prefix) =>
!reminder.Any() ? new[] { prefix.ToArray() } :
reminder.SelectMany((c, i) => permutate(
reminder.Take(i).Concat(reminder.Skip(i+1)).ToArray(),
prefix.Append(c)));
}
Any optimizations? Could it be shorter?
=>greatly hurts readability here. \$\endgroup\$Skipextension. I'm not sure you remember... but the built-in one doesn't recognizeIListso it always enumerates from the beginning. I useSkipFastwhere this matters. \$\endgroup\$