Last active
February 2, 2025 09:36
-
-
Save aannenko/18ca4813dc3e8a3bb03421ec586e2156 to your computer and use it in GitHub Desktop.
Returns all string permutations using the Heap's algorithm (linear).
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
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