Function to calculate permutations being weird

This is an algorithm (not my own) that prints out the possible permutations of a string. In function "permute" I cout[ed] some variables in order to know their values at different times during the execution of a program in order to learn its working. What I find is assuming is how can the value of "place" possibly be equal to 1 after it has had a value of 2. There is nothing that decrements "place". I have made a comment in the program so you guys know exactly what I am talking about.

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
#include <iostream>
#include <string>

using namespace std;

string swtch(string topermute, int x, int y)
{
	string newstring = topermute;
	newstring[x] = newstring[y];
	newstring[y] = topermute[x]; //avoids temp variable
	return newstring;
}
void permute(string topermute, int place)
{
	if(place == topermute.length() - 1)
	{
		cout<<topermute<<endl;
	}
	for(int nextchar = place; nextchar < topermute.length(); nextchar++)
	{
		cout << place << endl;  //How can this be 1 after being 2. 
                                        //We only increment place
		cout << nextchar << endl;
		permute(swtch(topermute, place, nextchar), place+1);
	}
}

int main()
{
		string str = "cat";
        permute(str, 0);
}
Last edited on
My version would be
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <algorithm>
#include <iostream>
#include <string>

int main()
{
    std::string str("cat");

    std::sort(str.begin(), str.end());
    do
    {
        std::cout << str << '\n';
    } while (std::next_permutation(str.begin(), str.end()));

    return 0;
};
Denis, the idea is to demonstrate the problem using recursion specifically. Using STL algorithms isn't much of a feat, my friend. The best part, however, is that the code actually does what it is supposed to do i.e. permute the string. I just wanna know how it does that.
Topic archived. No new replies allowed.