Willcode4cash

Permutations example

Aug 14th, 2016
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.95 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace Permutation
  6. {
  7.     public static class Extension
  8.     {
  9.         public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> source)
  10.         {
  11.             if (source == null)
  12.                 throw new ArgumentNullException("source");
  13.  
  14.             return PermutationsImpl(source, Enumerable.Empty<T>());
  15.         }
  16.  
  17.         private static IEnumerable<IEnumerable<T>> PermutationsImpl<T>(IEnumerable<T> source, IEnumerable<T> prefix)
  18.         {
  19.             if (!source.Any())
  20.                 yield return prefix;
  21.  
  22.             foreach (var permutation in source.SelectMany(x => PermutationsImpl(source.Except(Yield(x)), prefix.Union(Yield(x)))))
  23.             {
  24.                 yield return permutation;
  25.             }
  26.         }
  27.  
  28.         private static IEnumerable<T> Yield<T>(this T element)
  29.         {
  30.             yield return element;
  31.         }
  32.     }
  33. }
Add Comment
Please, Sign In to add comment