recursive permute function (looking for a different version)

Hi, I'm a beginner at c++. The following code outputs first string plus all possible permutations of the second string. I'm looking to produce the permutations of first string(instead of second) plus the second string. How can I do that?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
  void permute(string prefix, string rest)
{
	
	if (rest == "")
	{
		cout << prefix << endl;
	}
	else
	{
		for (int i = 0; i < rest.length(); i++)
		{
			//test if rest[i] is unique.
			bool found = false;
			for (int j = 0; j < i; j++)
			{
				if (rest[j] == rest[i])
					found = true;
			}
			if (found)
				continue;
			string newPrefix = prefix + rest[i];
			string newRest = rest.substr(0, i) + rest.substr(i + 1);
			permute(newPrefix, newRest);

		}

	}
}

int main()
{
	permute("TO", "MAC");
	return 0;
}
Swap the words prefix and rest.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include<iostream>
#include<string>
using namespace std;


void permute(string prefix, string rest)
{
        
        if (prefix == "")
        {
                cout << rest << endl;
        }
        else
        {
                for (int i = 0; i < prefix.length(); i++)
                {
                        //test if prefix[i] is unique.
                        bool found = false;
                        for (int j = 0; j < i; j++)
                        {
                                if (prefix[j] == prefix[i]) found = true;
                        }
                        if (found) continue;
                        string newRest = prefix[i] + rest;
                        string newPrefix = prefix.substr(0, i) + prefix.substr(i + 1);
                        permute(newPrefix, newRest);

                }

        }
}

int main()
{
        cout << "\nCheck original" << endl;
        permute("MAC", "TO");

        cout << "\nCheck repetition" << endl;
        permute("LOOT", "ABC");
        return 0;
}

Thanks :)
Topic archived. No new replies allowed.