Skip to content

Instantly share code, notes, and snippets.

@aannenko
Created December 5, 2024 20:28
Show Gist options
  • Save aannenko/0785dd8f5135e8ce6c31d5a6f20123be to your computer and use it in GitHub Desktop.
Save aannenko/0785dd8f5135e8ce6c31d5a6f20123be to your computer and use it in GitHub Desktop.
Returns all string permutations using the Heap's algorithm (recursive).
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