The topic in Chapter 12th of the programming Pearl River is to generate M (M <= N) ordered random sequences with a given number of 0-n-1, which cannot be repeated.
Method 1: use the set container in C ++ to insert the number of rand () % N into the set until the set size is m and break, the Set container Automatically sorts the elements.
Method 2: it is the solution given in the book, scanning the array [0, n), and then making remaining = N, select = M. If a number I is selected successfully each time, select-1, remaining --;
Method 3: for a specific array list [N], the element is 0-n-1. For the number of the first m, a random number (I, n-1) Rand is generated each time, then swap the elements of I and Rand, swap (I, RAND), and finally sort the number of the first M.
There is an interesting reverse thinking problem here, assuming n = 1 million, M = N-10, then we really want to generate a random number of 1 million-10, of course not, we only need to generate 10 random numbers, and then use the 1 million number to remove the 10 number, is not the N-10 random number?
#include<stdio.h>#include<time.h>#include<stdlib.h>#include<string.h>/* * Method No_01 */void random_01(int *list,int n,int m){int i,j = 0;int remaining = n,select = m;for(i = 0;i<n;i++){if(rand()%remaining < select){list[j++] i;select--;}remaining--;}}/* *method No_02 set in c++ */ void random_02(set<int> &s,int n,int m){while(1){s.insert(rand()%n);if(s.size() == m)break;}}/* * Method NO_02 */int randint(int x,int y){return rand()%(y-x+1) + x;}/* the elements of list are from to n-1,in order */void random_02(int *list,int n,int m){srand((unsigned int)time(NULL));int i, j;for(i = 0;i<m;i++){swap(&list[i],&list[randint(i+1,n-1)]);}qsort(list,m,sizeof(list[0]),cmp);// sort}