Dar*_*ria 4 c# string permutation
我有5个字符串,例如:"one","two","three","four"和"five".我需要得到这些字符串的所有排列.我已经探索了所有的互联网资源,但是所有的解决方案都非常庞大,我很难理解它并将其集成到我的程序中.
所以,也许你知道如何获得排列的任何简单的解决方案.
Tim*_*mwi 17
排列很容易做到.
/// <summary>
/// Returns all permutations of the input <see cref="IEnumerable{T}"/>.
/// </summary>
/// <param name="source">The list of items to permute.</param>
/// <returns>A collection containing all permutations of the input <see cref="IEnumerable<T>"/>.</returns>
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);
}
Run Code Online (Sandbox Code Playgroud)