Last active
February 13, 2018 09:14
-
-
Save kpol/32f8d121de0923ad79bb5659ffa1f20a to your computer and use it in GitHub Desktop.
Gets all permutations. Heap's algorithm.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /// <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++; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment