Skip to content

Instantly share code, notes, and snippets.

@aannenko
Last active February 2, 2025 09:36
Show Gist options
  • Save aannenko/18ca4813dc3e8a3bb03421ec586e2156 to your computer and use it in GitHub Desktop.
Save aannenko/18ca4813dc3e8a3bb03421ec586e2156 to your computer and use it in GitHub Desktop.
Returns all string permutations using the Heap's algorithm (linear).
GetPermutations(['a', 'b', 'c', 'd']).Dump();
static IEnumerable<string> GetPermutations(char[] chars)
{
yield return new string(chars);
if (chars.Length < 2)
yield break;
var counter = new int[chars.Length];
var i = 0;
while (i < chars.Length)
{
if (counter[i] < i)
{
if (i % 2 == 0)
(chars[0], chars[i]) = (chars[i], chars[0]);
else
(chars[counter[i]], chars[i]) = (chars[i], chars[counter[i]]);
yield return new string(chars);
counter[i]++;
i = 1;
}
else
{
counter[i] = 0;
i++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment