从 C# 中的给定字母生成所有可能的排列

Generate all possible permutations from given letters in C#

假设我在字符串中有以下字符:

string s = "acn"

我想用 C# 编写一个函数来显示以下文字:

acn

anc

cna

can

nac

nca

这些我都试过了,但还是一头雾水。

Using Permutations in .NET for Improved Systems Security

Implement a function that prints all possible combinations of the characters in a string

枚举扩展

public static class EnumerableExtensions
{
    // Source: 
    private static IEnumerable<TSource> Prepend<TSource>(this IEnumerable<TSource> source, TSource item)
    {
        if (source == null)
            throw new ArgumentNullException("source");

        yield return item;

        foreach (var element in source)
            yield return element;
    }

    public static IEnumerable<IEnumerable<TSource>> Permutations<TSource>(this IEnumerable<TSource> source)
    {
        if (source == null)
            throw new ArgumentNullException("source");

        var list = source.ToList();

        if (list.Count > 1)
            return from s in list
                   from p in Permutations(list.Take(list.IndexOf(s)).Concat(list.Skip(list.IndexOf(s) + 1)))
                   select p.Prepend(s);

        return new[] { list };
    }
}

用法

class Program
{
    static void Main(string[] args)
    {
        string s = "acn";

        foreach (var permutation in s.Permutations())
            Console.WriteLine(string.Concat(permutation));
    }
}

输出

acn
anc
can
cna
nac
nca