Guest User

Untitled

a guest
Feb 24th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. /// <summary>
  2. /// Heap's algorithm.
  3. /// </summary>
  4. /// <typeparam name="T"></typeparam>
  5. /// <param name="source"></param>
  6. /// <returns></returns>
  7. public static IEnumerable<T[]> GetAllPermutations<T>(IEnumerable<T> source)
  8. {
  9. var result = source.ToArray();
  10.  
  11. yield return result;
  12.  
  13. var copy = result.ToArray();
  14. var c = new int[copy.Length];
  15.  
  16. int i = 0;
  17.  
  18. while (i < copy.Length)
  19. {
  20. if (c[i] < i)
  21. {
  22. if (i % 2 == 0)
  23. {
  24. var a = copy[0];
  25. copy[0] = copy[i];
  26. copy[i] = a;
  27. }
  28. else
  29. {
  30. var a = copy[c[i]];
  31. copy[c[i]] = copy[i];
  32. copy[i] = a;
  33. }
  34.  
  35. yield return copy.ToArray();
  36.  
  37. c[i]++;
  38. i = 0;
  39. }
  40. else
  41. {
  42. c[i] = 0;
  43. i++;
  44. }
  45. }
  46. }
Add Comment
Please, Sign In to add comment