Created
December 5, 2024 20:28
-
-
Save aannenko/0785dd8f5135e8ce6c31d5a6f20123be to your computer and use it in GitHub Desktop.
Returns all string permutations using the Heap's algorithm (recursive).
This file contains 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
char[] chars = ['a', 'b', 'c', 'd']; | |
GetPermutationsRecursive(chars.Length, chars).Dump(); | |
static IEnumerable<string> GetPermutationsRecursive(int take, char[] chars) | |
{ | |
if (take is 1) | |
{ | |
yield return new string(chars); | |
} | |
else | |
{ | |
var lastIndex = take - 1; | |
foreach (var item in GetPermutationsRecursive(lastIndex, chars)) | |
yield return item; | |
for (var i = 0; i < lastIndex; i++) | |
{ | |
if (take % 2 == 0) | |
(chars[i], chars[lastIndex]) = (chars[lastIndex], chars[i]); | |
else | |
(chars[0], chars[lastIndex]) = (chars[lastIndex], chars[0]); | |
foreach (var item in GetPermutationsRecursive(lastIndex, chars)) | |
yield return item; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment