Transferred from: http://cid-2801919e8e836c16.spaces.live.com/blog/cns! 2801919e8e836c16! 151. Entry
Solution 1:
The random number can be obtained using the C ++ standard Rand. As for M, you can use STD: Set to solve the problem.
Insert it into the set. set size () = m. You can perform the following operations:
# Include <set>
# Include <stdlib. h>
Int main ()
{
STD: Set <int> S;
While (1)
{
Int r = rand () % N;
S. insert (R );
If (S. Size () = m)
{
Break;
}
}
}
Because the underlying implementation of set is a red/black tree, the insertion complexity is logarithm-level ^_^.
----------------------------------------------------------------
Solution 2:
# Include <iostream>
# Include <cstdlib> // used for rand () and srand () Functions
# Include <ctime> // set different random numbers
Using namespace STD;
Int main (){
Srand (time (0); // call a random number function that is not repeated.
Unsigned I;
For (INT n = 0; n ++ <10 ;)
{
I = rand (); // random number assigned to the I System
Cout <"the No." <n <"is:" <I <Endl;
}
Return 0;
}
1. The C ++ standard function library provides a random number generator Rand, which returns a pseudo random integer evenly distributed between 0 and rand_max. Rand_max
It must be at least 32767. The rand () function does not accept parameters. The default value is 1 (the start value ).
The random number generator always starts with the same seed, so the pseudo-random sequence is also formed. The random meaning is lost.
2. Another function srand () in C ++ can specify different numbers (unsigned integer yuan) as seeds. However, if the seeds are the same
The random sequence is also the same. -- One method is to allow users to input seeds, but it is still unsatisfactory.
3. It is ideal to use a variable number, such as time, as the seed of the random number generator.
In the header file ctime, the time library contains the time function. It can return a value indicating the time, date, month, and year. For example:
You can set this value as the seed of Rand.
Srand (static_cast <unsigned> (Time (static_cast <time_t *> (null ))));
4. However, srand () does not mean that random numbers are different. It only changes the seed of random numbers over time :)
So, a good solution!