Generate N different random numbers (C + +, range 0~n-1)

Source: Internet
Author: User
Tags strcmp

The process of doing a project often has a random selection process. This note mainly gives two methods of randomly generating n different random numbers, and then simply introduces the function Srand,rand and time used in the random numbers in C + +. In the end, a simple example is given, which is to randomly select K images from a folder containing n images to be stored in another folder.

A: A method of generating n different random numbers

#include <stdio.h> #include <stdlib.h> #include <time.h> #define N 20#define K 10void swap (int *a, int *b)    {if (*a! = *b) {//XOR/Operation interchange two digit position *a ^= *b;*b ^= *a;*a ^= *b;} }/******************************************************************************* function name: void GenerateDiffRandV1 ( int a[], int n) * Function function: produce different random number * Entry parameters: * return value: None * Note: space change time ************************************************************    /void generateDiffRandV1 (int a[], int n, int k) {int i;    time_t T;    for (i = 0; i < n; i++) {a[i] = i;    } srand ((int) time (&t));    for (i = 0; i < K; i++) {swap (&a[i], &a[i+rand ()% (n-i)]); }}/******************************************************************************* function name: void GenerateDiffRandV2 ( int a[], int n) * Function function: Produces a different random number (the range that produces the random number is 1~n-1) * Entry parameter: * return value: no * * idea: Sir into a set of the array, and then randomly extracted, after extraction to prevent duplication, immediately zero. *: Each time you generate a seat, just determine whether it is 0, greatly improving the efficiency of program execution. ***********************************************************/void generateDiffRandV2 (int a[], int n) {int *flag = (int *) malloc (sizeof (int) * n);    static int flag_once = 0;        int I, index;    for (i = 0; i < n; i++) flag[i] = i+1;        if (!flag_once) {Srand (time (0));    Flag_once = 1;        } for (i = 0; i < n;) {index = rand ()% n;            if (Flag[index]! = 0) {a[i++] = flag[index]-1;        Flag[index] = 0; }} free (flag);}    void PrintArray (int a[], int n) {int i;    for (i = 0; i < n; i++) {printf ("%d", a[i]); } printf ("\ n");}    int main () {int a[n];    GenerateDiffRandV1 (A, N, K);        PrintArray (A, N);    GenerateDiffRandV2 (A, N);        PrintArray (A, N); return 0;}


II: Introduction to Srand,rand and time functions

The 1:srand function is the initialization function of the random number generator. It needs to provide a seed, which will correspond to a random number, and if the same seed is used, the following rand () function will appear the same random number. such as: Srand (1); Srand (1) is also the default seed to initialize seeds directly using one. Included in the library <stdlib.h>.

Such as:

#include <iostream> #include <time.h>using namespace Std;int main () {//Srand equivalent to a random number of initialization functions, sowing seeds for random numbers,//srand ((unsigned) time (0));    Time returned is time_t type Srand (1),//time_t t= time (0), for (int i = 0; i < i++) {cout << rand () << Endl;} return 0;}

no matter how many times this code runs, it's always from the seed 1 start generating random numbers, so the results are the same.

to avoid this situation, we used the Srand ((unsigned) time (0)); 0 Representative null,time (NULL) is to get the current time meaning , this will produce a different random number for each run . Time () Returns the result of time_t, cast for unsigned type, contained in library <time.h>.

The 2:rand function is a pseudo-random number generator that needs to call Srand initialization, typically initializing the random number seed with the current calendar time, so that each line of code can produce a different random number.

Three: Example (a folder containing n pictures randomly selected K pictures into another folder)

/* Randomly select 1w images from the gallery */#include <stdio.h> #include <stdlib.h>//Use the Srand function, so this header file # include <io stream> #include "browsedir.hpp" #include <cv.h> #include 

Directory Operation code BROWSEDIR.HPP:

#pragma once#include <stdio.h> #include <stdlib.h> #include <direct.h> #include <string.h># Include <iostream> #include <io.h> #include <vector> #include <fstream> #include <string> Using namespace Std;class cbrowsedir{protected://holds the absolute path to the initial directory, ending with ' \ ' char M_szinitdir[_max_path];p ublic:// The default constructor Cbrowsedir ();//Set the initial directory to Dir, if return False, indicates that the directory is not available bool Setinitdir (const char *dir);//start traversing files of the type specified by filespec under the initial directory and its subdirectories Filespec You can use wildcard characters *?, you cannot include a path. If False, indicates that the traversal process was aborted by the user virtual bool Beginbrowse (const char *filespec);p rotected://traverse directory dir under the file specified by filespec//For subdirectories, Use iterative method//If return FALSE, indicates abort traversal file bool Browsedir (const char *dir,const char *filespec);//function Browsedir every file found, call Processfile and pass the file name as a parameter passed past//if return false, indicates abort traverse file//user can overwrite the function, add their own processing code virtual BOOL Processfile (const char *filename);// The function Browsedir each entry into a directory, invokes processdir//and passes the directory name being processed and the previous directory name as a parameter pass///If the initial directory is being processed, the parentdir=null//user can override the function to add their own processing code For example, the user can count the number of subdirectories here virtual void Processdir (const char *currentdir,const char *PARENTDIR);}; Cbrowsedir::cbrowsedir () {///Initialize M_SZINITDIRGETCWD (M_szinitdir,_max_path) with the current directory;//If the last letter of the directory is not ' \ ', add a ' \ ' int at the end Len=strlen (M_szinitdir); if (m_szinitdir[len-1]! = ' \ \ ') strcat (m_szinitdir, "\ \");} BOOL Cbrowsedir::setinitdir (const char *dir) {//dir is first converted to absolute path if (_fullpath (m_szinitdir,dir,_max_path) = = NULL) return false;//determine if the directory exists if (_chdir (m_szinitdir)! = 0) Return false;//if the last letter of the directory is not ' \ ', then at the end add a ' \ ' int len=strlen (M_SZINITDIR) if (m_szinitdir[len-1]! = ' \ \ ') strcat (m_szinitdir, "\ \"); return true;} BOOL Cbrowsedir::beginbrowse (const char *filespec) {processdir (m_szinitdir,null); return Browsedir (M_szinitdir, filespec);} BOOL Cbrowsedir::browsedir (const char *dir,const char *filespec) {_chdir (dir);//First Look for the files in dir that meet the requirements long hfile;_finddata_t Fileinfo;if ((Hfile=_findfirst (filespec,&fileinfo))! =-1) {do{//Check is not a directory//if not, then process if (! ( Fileinfo.attrib & _a_subdir) {char filename[_max_path];strcpy (filename,dir); strcat (filename,fileinfo.name);// cout << filename << endl;if (! Processfile (FilenaMe)) return false;}} while (_findnext (hfile,&fileinfo) = = 0); _findclose (hfile);} Find subdirectories in Dir//Because the processfile of the derived class may have changed//current directory when processing the file in Dir, so also reset the current directory to dir. Once the _findfirst has been performed, the relevant information may be recorded, so changing the directory//has no effect on _findnext. _chdir (dir); if ((Hfile=_findfirst ("* *", &fileinfo))! =-1) {do{//Check is not a directory//If yes, then check if it is not. Or, if not, iterate if ( Fileinfo.attrib & _a_subdir) {if (strcmp (Fileinfo.name, ".")! = 0 && strcmp (fileinfo.name, "...")! = 0) {char subdir[_max_path];strcpy (subdir,dir); strcat (subdir,fileinfo.name); Strcat (subdir, "\ \"); Processdir (Subdir,dir); if (! Browsedir (Subdir,filespec)) return false;}} while (_findnext (hfile,&fileinfo) = = 0); _findclose (hfile);} return true;} BOOL Cbrowsedir::P rocessfile (const char *filename) {return true;} void Cbrowsedir::P rocessdir (const char *currentdir,const char *parentdir) {}//a subclass derived from Cbrowsedir,   Used to count the number of files and subdirectories in the directory class Cstatdir:public Cbrowsedir{protected:int m_nfilecount; Save file number int m_nsubdircount; Save subdirectory number public:vector<string> vec_files;public://default constructor CStatdir () {//Initialize data members M_nfilecount and m_nsubdircountm_nfilecount=m_nsubdircount=0;} Returns the number of files int getfilecount () {return m_nfilecount;} Returns the number of subdirectories int getsubdircount () {///Because the function is also called when the initial directory is entered processdir,//so minus 1 is the true number of subdirectories. return m_nsubdircount-1;} void Visitedfiles (Ostream&out) {for (Vector<string>::iterator iter=vec_files.begin (); iter!=vec_files.end (); iter++) {out<<*iter<< "\ n";}} virtual bool Beginbrowse (const char *filespec) {string file_exts=filespec;vector<string> vec_exts;size_t Pos_ start=0;size_t Npos=file_exts.find ("|"); String Exts;while (Npos!=string::npos) {exts=file_exts.substr (Pos_start,npos-pos_start); Vec_exts.push_back (exts); Pos_start=npos+1;npos=file_exts.find ("|", Pos_start);} Exts=file_exts.substr (Pos_start); Vec_exts.push_back (exts); bool Sign=true;for (Vector<string>::iterator ITER =vec_exts.begin (); Iter!=vec_exts.end (); iter++) {exts=*iter;if (! Cbrowsedir::beginbrowse (Exts.c_str ())) {Sign=false;}} return sign;} protected://Overwrite virtual function processfile, each call, the number of files plus 1virtual bool ProceSsfile (const char *filename) {m_nfilecount++;//cout<<filename<<endl;vec_files.push_back (filename); Return Cbrowsedir::P rocessfile (filename);} Overwrite virtual function Processdir, per call, number of subdirectories plus 1virtual void processdir (const char *currentdir,const char *parentdir) {m_nsubdircount+ +; Cbrowsedir::P rocessdir (Currentdir,parentdir);};


Reference documents:

1:http://blog.chinaunix.net/uid-21228455-id-2406483.html generates a distinct random number of k less than n

2:http://blog.csdn.net/kongfanyu/article/details/6387642

3:http://wenku.baidu.com/link?url=eyvsyysirpdfidgav7begz16gciinu_ Azcpdtpphl4v5y9tvvqzxweviyb74aqvuw2lnpshtwrsxa05t0bz3yqgxui_hvbyd5usn1pmu_m_

Generate N different random numbers (C + +, range 0~n-1)

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.