Hi,
I am trying to understand how to permute a set. Many people say it's easy but I can't get it. I took the code from here http://www.cprogramming.com/challenges/permutesol.html:
Code:
#include <iostream>
#include <string>
using namespace std;
/* this function accepts string and moves a letter at place 'x' to place 'y' */
string swap_places(string topermute, int x, int y)
{
string newstring = topermute;
newstring[x] = newstring[y];
newstring[y] = topermute[x]; // avoids temp variable
return newstring;
}
int counter = 0;
void permute(string topermute, int place)
{
if (place == topermute.length() - 1)
{
cout << ++counter << ". " << topermute << endl;
}
for (int nextchar = place; nextchar < topermute.length(); nextchar++)
{
permute(swap_places(topermute, place, nextchar), place+1);
}
}
int main(int argc, char* argv[])
{
if (argc != 2)
{
cout << "Proper input is '" << argv[0] << "' string'";
return 1;
}
permute(argv[1], 0);
}
'permute' function looks quite complicated to me, there's a recursion in the loop and I'm confused. Could someone please explain it to me?