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

时间:2018-02-17 09:29:39

标签: c# permutation words

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

string s = "acn"

我想在C#中编写一个函数来显示以下单词:

  

ACN

     

ANC

     

CNA

     

可以

     

NAC

     

NCA

我试过这些,但我仍感到困惑。

Using Permutations in .NET for Improved Systems Security

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

1 个答案:

答案 0 :(得分:1)

EnumerableExtensions

public static class EnumerableExtensions
{
    // Source: http://stackoverflow.com/questions/774457/combination-generator-in-linq#12012418
    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