You are using a version without Ads of this website. Please, consider donating:

### Generate a random permutation in an array

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

 ``1234567891011121314151617181920212223242526272829303132333435363738`` ``````#include #include #include 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
Last edited on
 ``1234567891011121314151617`` ``````#include #include #include #include //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<
@OP: you are only checking the previous position.
I suggest you to make use of a check function
 ``123456`` ``````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
Ill try the search function. Thanks bro
Topic archived. No new replies allowed.