# Help in understanding permutations

This is a discussion on Help in understanding permutations within the C++ Programming forums, part of the General Programming Boards category; Hi, I am trying to understand how to permute a set. Many people say it's easy but I can't get ...

1. ## Help in understanding permutations

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?

2. Step through the code (or with the debugger) for an input string of "a"
I'm sure you can work out all the permutations of "a" in your head.

Then try the same experiment with "ab", and "abc".

> permute(swap_places(topermute, place, nextchar), place+1);
It might help to separate this out into
string temp = swap_places(topermute, place, nextchar);
permute(temp, place+1);

so you can see what is going on.