Chapter 1 of programming Pearl River generates ordered Random Sequences

Source: Internet
Author: User

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}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.