iterate through possible anagrams of a given string in csharp

Here is a possible solution to iterate through possible anagrams of the given string using recursion:

main.cs
public static List<string> GetAnagrams(string str)
{
    List<string> anagrams = new List<string>();
    GetAnagramsHelper("", str, anagrams);
    return anagrams;
}

private static void GetAnagramsHelper(string prefix, string suffix, List<string> anagrams)
{
    if (suffix.Length == 0)
    {
        anagrams.Add(prefix);
    }
    else
    {
        for (int i = 0; i < suffix.Length; i++)
        {
            string newPrefix = prefix + suffix[i];
            string newSuffix = suffix.Substring(0, i) + suffix.Substring(i + 1);
            GetAnagramsHelper(newPrefix, newSuffix, anagrams);
        }
    }
}
616 chars
24 lines

The GetAnagrams function takes the string for which you want to generate anagrams as input and returns a list of all anagrams.

The GetAnagramsHelper function implements the algorithm to generate anagrams. It takes two strings as input, prefix and suffix, which are used to build the anagrams. Initially, prefix is an empty string and suffix is the original input string.

The function uses a for loop to iterate through each character of suffix and recursively call GetAnagramsHelper with the new prefix and suffix obtained by appending and removing the current character, respectively. When suffix becomes empty, prefix contains one of the anagrams, and it is added to the list.

To generate all possible anagrams, the GetAnagrams function calls GetAnagramsHelper with an empty prefix and the original input string as suffix.

gistlibby LogSnag