Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// <summary>
- /// Heap's algorithm.
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="source"></param>
- /// <returns></returns>
- public static IEnumerable<T[]> GetAllPermutations<T>(IEnumerable<T> source)
- {
- var result = source.ToArray();
- yield return result;
- var copy = result.ToArray();
- var c = new int[copy.Length];
- int i = 0;
- while (i < copy.Length)
- {
- if (c[i] < i)
- {
- if (i % 2 == 0)
- {
- var a = copy[0];
- copy[0] = copy[i];
- copy[i] = a;
- }
- else
- {
- var a = copy[c[i]];
- copy[c[i]] = copy[i];
- copy[i] = a;
- }
- yield return copy.ToArray();
- c[i]++;
- i = 0;
- }
- else
- {
- c[i] = 0;
- i++;
- }
- }
- }
Add Comment
Please, Sign In to add comment