Created
May 20, 2019 09:41
-
-
Save arialdomartini/2f93c69bb9d56989d03256fa1f239617 to your computer and use it in GitHub Desktop.
Permutations of a string, with iterative algorithm
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
private static IEnumerable<string> PermutationsIterative(string s) | |
{ | |
var permutations = new List<(string permutation, string rest)> | |
{ | |
("", s) | |
}; | |
while (true) | |
{ | |
if (permutations.All(p => p.rest == "")) | |
return permutations.Select(p => p.permutation); | |
permutations = permutations.SelectMany(p => | |
p.rest.Select(c => | |
( | |
p.permutation + c, | |
p.rest.RemoveChar(c) | |
))).ToList(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment