Generate a random permutation in an array

Feb 16, 2013 at 6:31am
Hi guys, I'm currently working on assignment which requires to generate a random permutation of the first N integers. For example, if N = 4, one possible answer is {3,1,2,4} without duplicates. {3,3,2,4} is not correct

to fill a[4], generate random numbers until you get one that is not already in a[0], a[1], ..., a[n-1]. for a[0] whatever random number you generate can be put in it. So here is my code. It seem to works but sometime it give duplicates. Any help would be appreciated guys. 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
#include <iostream>
#include <stdlib.h> 
#include <time.h> 


using namespace std;
int main()
{
	/* initialize random seed */
	 srand(time(NULL));
	//const int N = 250;
	int a[4];
	
	
	int num = rand()%4+1;
	a[0] = num;

	for(int i=1; i<4; i++)
	{
		num = rand()%4+1;
		for(int j=0; j<i; j++)
		{
			while(num == a[j])
			{
				num = rand()%4+1;
				
			}
			a[i]=num;
		}
	}

	for(int i=0; i<4; i++)
		cout<<a[i]<<" ";
	cout<<endl;

	system("PAUSE");
	return 0;
}
Last edited on Feb 16, 2013 at 6:51am
Feb 16, 2013 at 6:59am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <stdlib.h> 
#include <time.h> 
#include <algorithm>  //for random_shuffle http://cplusplus.com/reference/algorithm/random_shuffle/
using namespace std;

int main()
{
  srand(time(NULL));

  int a[4] = {1,2,3,4};

  random_shuffle(a, a+4); 

  for(int i=0; i<4; i++) cout<<a[i]<<" ";
  cout<<endl;
}
Feb 16, 2013 at 7:10am
@OP: you are only checking the previous position.
I suggest you to make use of a check function
1
2
3
4
5
6
bool find(int *begin, int *end, int value); //[)
//use it as
for(int K=1; K<4; ++K)
   do
      a[K]=rand()%4+1;
   while( find(a, a+K, a[K]) );
Last edited on Feb 16, 2013 at 7:12am
Feb 16, 2013 at 1:08pm
Ill try the search function. Thanks bro
Topic archived. No new replies allowed.