7/29/2014

no duplication random, (stl random_shuffle example source code)

sometimes, we need no duplication random sequence data.
simple method is using shuffle random in stl.

refer to this source code.

#include < stdio.h>
#include < vector>
#include < algorithm>
#include < cstdlib>
#include < ctime>
#include < iostream>
using namespace std;


void main()
{
 //set size and initialize
 vector< int > A(10);
 for(int i=0; i< A.size(); ++i)
  A[i] = i;

 //confirm
 printf("----origin data \n");
 for(int i=0; i< A.size(); ++i)
  printf("[%d] - %d \n", i, A[i] );
 printf("----\n");

 //random 
 srand( unsigned (time(0) ) );
 random_shuffle( A.begin(), A.end() );

 //confirm
 printf("---- After shuffle \n");
 for(int i=0; i< A.size(); ++i)
  printf("[%d] - %d \n", i, A[i] );
 printf("----\n");
}


..

No comments:

Post a Comment