生成不重复的随机数对(C/C++)
1 #include <stdio.h> 2 #include <algorithm> 3 #include <stdlib.h> 4 #include <time.h> 5 using namespace std; 6 const int max_rand = 2001; 7 int a[max_rand], b[max_rand]; 8 struct node 9 { 10 int x, y; 11 bool operator < (const node q) const 12 { 13 if(x == q.x) 14 return y < q.y; 15 return x < q.x; 16 } 17 }RAND[20010]; 18 19 int main() 20 { 21 for (int i = 0; i < max_rand; i ++) 22 a[i] = b[i] = i; 23 b[0] = -1; 24 int aa = 2, bb = 10; 25 // time_t t; 26 // srand((unsigned) time(&t)); 27 srand((unsigned)time(NULL));// let the seed accroding to time 28 for (int i = 0; i < 2000; i ++) 29 { 30 int x = rand()%2001; //make x between 0 and 2000(include) 31 int y = rand()%2001; //same up; 32 /* double text = (double)rand()/RAND_MAX*(bb-aa) +aa; //produce double text between aa and bb 33 printf ("%f\n", text); 34 getchar(); 35 */ 36 if((!x || !y)||(!a[x] && b[y] == -1)) 37 { 38 i --; 39 continue; 40 } 41 RAND[i] = (node){x, y}; 42 43 a[x] = 0; 44 b[y] = -1; 45 } 46 sort(RAND, RAND +2000); 47 for (int i = 0; i < 2000; i ++) 48 { 49 printf("%d %d\n", RAND[i].x, RAND[i].y); 50 // getchar(); 51 } 52 return 0; 53 }