Thursday, June 25, 2015
[Coding Quiz] get all permutations of a given string
public IEnumerable<string> getAllPermutationsOfString(string input)
{
// given a string as input, print out all possible permutations of that string
// for example: input of "abc" gives six outputs: abc, acb, bac, bca, cba, cab
if (input == null) throw new ArgumentNullException();
if (input.Length == 1)
{
yield return input;
}
else
{
for (int i=0; i<input.Length; i++)
{
var remainder = input.Remove(i, 1);
foreach (var permus in getAllPermutationsOfString(remainder))
{
yield return (input[i] + permus);
}
}
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment