Willcode4cash icon

Permutations example

Willcode4cash | PRO | 08/15/16 04:04:30 AM UTC | 0 ⭐ | 282 👁️ | Never ⏰ | []
C# |

950 B

|

None

|

0 👍

/

0 👎

using System;
using System.Collections.Generic;
using System.Linq;
 
namespace Permutation
{
    public static class Extension
    {
        public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> source)
        {
            if (source == null)
                throw new ArgumentNullException("source");
 
            return PermutationsImpl(source, Enumerable.Empty<T>());
        }
 
        private static IEnumerable<IEnumerable<T>> PermutationsImpl<T>(IEnumerable<T> source, IEnumerable<T> prefix)
        {
            if (!source.Any())
                yield return prefix;
 
            foreach (var permutation in source.SelectMany(x => PermutationsImpl(source.Except(Yield(x)), prefix.Union(Yield(x)))))
            {
                yield return permutation;
            }
        }
 
        private static IEnumerable<T> Yield<T>(this T element)
        {
            yield return element;
        }
    }
}

Comments