-
-
Save searope/34e787b49683d9ee725a3f7c07f944c3 to your computer and use it in GitHub Desktop.
Generating permutations of arr in lexicographic order in C#
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
| public IEnumerable<int[]> Permut(int[] arr){ | |
| while (true){ | |
| yield return arr; | |
| var j = arr.Length - 2; | |
| while (j >= 0 && arr[j] >= arr[j+1]) j--; | |
| if (j < 0) break; | |
| var l = arr.Length -1; | |
| while (arr[j] >= arr[l]) l--; | |
| var tmp = arr[l]; arr[l] = arr[j]; arr[j] = tmp; | |
| var k = j +1; | |
| l = arr.Length -1; | |
| while (k < l){ | |
| var t = arr[k]; | |
| arr[k] = arr[l]; | |
| arr[l] = t; | |
| k++; | |
| l--; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment