Skip to content

Instantly share code, notes, and snippets.

@arialdomartini
Created May 20, 2019 09:41
Show Gist options
  • Save arialdomartini/2f93c69bb9d56989d03256fa1f239617 to your computer and use it in GitHub Desktop.
Save arialdomartini/2f93c69bb9d56989d03256fa1f239617 to your computer and use it in GitHub Desktop.
Permutations of a string, with iterative algorithm
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