Skip to content

Instantly share code, notes, and snippets.

@arialdomartini
Created May 20, 2019 08:49
Show Gist options
  • Save arialdomartini/f3afaff77566a9c8b91f3f09e3b6b3e9 to your computer and use it in GitHub Desktop.
Save arialdomartini/f3afaff77566a9c8b91f3f09e3b6b3e9 to your computer and use it in GitHub Desktop.
Calculate permutations recursively
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