Created
May 20, 2019 08:49
-
-
Save arialdomartini/f3afaff77566a9c8b91f3f09e3b6b3e9 to your computer and use it in GitHub Desktop.
Calculate permutations recursively
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> Permutations(string s) | |
=> Permutations("", s).Select(e => e.Item1); | |
private static IEnumerable<(string, string)> Permutations(string acc, string rest) | |
{ | |
if (string.IsNullOrEmpty(rest)) | |
return new[] {(acc, rest)}; | |
return rest.SelectMany(c => | |
Permutations( | |
acc + c.ToString(), | |
rest.RemoveChar(c.ToString()) | |
)); | |
} | |
[Fact] | |
void as_a_function() | |
{ | |
var result = Permutations("abc"); | |
result.Should().BeEquivalentTo(new List<string> | |
{ | |
"abc", | |
"acb", | |
"bac", | |
"bca", | |
"cab", | |
"cba" | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment