Search code examples
c++recursionanagram

How can I get all the anagrams of a string


Im trying to find all the possible anagrams of a string and store them in an array using only recursion.

Im stuck and this is all i have.

int main()
{
    const int MAX = 10;
    string a = "ABCD";
    string arr[10];

    permute(arr, a, 0, a.size(), 0);

    return 0;
}

void permute(string arr[], string wrd, int firstLetter, int lastLetter, int it)
{
    if (firstLetter == lastLetter)
        *arr = wrd;
    else
    {
            swap(wrd[firstLetter], wrd[it]);
            permute(arr, wrd, firstLetter + 1, lastLetter, it++);
    }
}

The order doesnt matter. Ex: string "abc"; array should have: abc, acb, bca, bac, cab, cba

Edit: im trying to find all permutations of a word and insert them into an array without using loops.


Solution

  • You should use string& for the parameter as it will be more efficient. You should iterate through chars.

    #include <iostream>
    #include <string>
    using namespace std;
    
    void permute(string* arr, int& ind, string& wrd, int it) {
        if (it == wrd.length()) {
            arr[ind++] = wrd;
        } else {
            for (int i = it; i < wrd.length(); ++i) {
                swap(wrd[i], wrd[it]);
                permute(arr, ind, wrd, it + 1);
                swap(wrd[i], wrd[it]);
            }
        }
    }
    
    int main() {
        string a = "ABCD";
        string arr[100]; // enough size to store all permutations
        int ind = 0;
        permute(arr,ind, a, 0);
        for (int i = 0; i < ind; ++i) {
            cout << arr[i] << endl;
        }
        return 0;
    }