3rd permutation generator


Hi all,
Below is the code that generates permutations of n elements. Please describe how it works. Thanks

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
42
43
44
45
46
47
48
49
50
51
52
#include "stdafx.h"
#include <stdio.h>
#include <time.h>
#include <iostream>
#include <string>
using namespace std;

int main() {

 

string aa;
test:
cout<<"Stringu=";
std::cin>>aa;
double tstart, tstop, ttime;
  tstart = (double)clock()/CLOCKS_PER_SEC;


int perm=1, digits=aa.size();
for (int i=1;i<=digits;perm*=i++);
{
for (int a=0;a<perm;a++)
{

	std::string avail=aa;
	for (int b=digits,div=perm;b>0; b--) 
	{
		div/=b;
		int index = (a/div)%b;
		printf("%c", avail[index] );
		//avail[index]=avail[b-1]; // non-lexigraphic but fast
		avail.erase(index,1) ; // lexigraphically correct
	}
	printf("\n");

}
}
	tstop = (double)clock()/CLOCKS_PER_SEC;
	   ttime= tstop-tstart; /*ttime is how long your code run*/
 cout << "Took "<< tstop-tstart << " seconds to compute";
 printf("\n");
printf("permutations:%d\n",perm);
char bb;
cout<<"Do you want to repeat it (y/n)";
cin>>bb;
if(bb=='y')
	goto test;

 return (0);
 
}

After a little code cleaning, take a look. Start at the top, and go until you get confused. Then ask the question.

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

using namespace std;

int main() {
	string aa;

	cout<<"Stringu=";
	std::cin>>aa;

	int perm=1, digits=aa.size();

	for (int i=1; i<=digits; perm*=i++);
	{
		for (int a=0; a<perm; a++)
		{
			std::string avail=aa;
			
			for (int b=digits,div=perm; b>0; b--)
			{
				div /= b;
				int index = (a/div)%b;
				printf("%c", avail[index] );
				//avail[index]=avail[b-1]; // non-lexigraphic but fast
				avail.erase(index,1) ; // lexigraphically correct
			}
			printf("\n");
		}
	}

	printf("permutations:%d\n",perm);
	
	return (0);

}
I'm new in C++. Can you describe what every line does? thanks
I don't mean this to sound rude. I could describe each line, but I wont.

I don't think that would be the best use of both of our time. Perhaps someone else on this board will chime in and do so.

In the mean time, take a spin through an online c++ tutorial. It will have you building easier examples than this one. With that in your head, you'll probably be able to see for yourself what is going on in this example.

http://www.cplusplus.com/doc/tutorial/
Topic archived. No new replies allowed.