Search code examples
c#permutationwords

Generate all possible permutations from given letters in C#


Suppose I have following characters in a string:

string s = "acn"

I want to write a function in C# to display following words:

acn

anc

cna

can

nac

nca

I have tried these but I am still confused.

Using Permutations in .NET for Improved Systems Security

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


Solution

  • 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 };
        }
    }
    

    Usage

    class Program
    {
        static void Main(string[] args)
        {
            string s = "acn";
    
            foreach (var permutation in s.Permutations())
                Console.WriteLine(string.Concat(permutation));
        }
    }
    

    Output

    acn
    anc
    can
    cna
    nac
    nca