This article reprinted http://blog.csdn.net/zhoufoxcn/article/details/5825093#comments
Sometimes we need to randomly generate a number from a specified value range and use this pseudo-random number to implement what we want to implement. I read a lot of articles and code in the garden and found that zhoufoxcn has a good idea of implementing this algorithm, especially the third method,
This skill is recorded for good efficiency, although we can use such as Random rand = new Random (Guid. newGuid (). getHashCode (); int value = rand. next (intMin, intMax) code implementation, but the programmer's maximum
The fun is to write different algorithms with different ideas.
The Code is as follows:
View Code
Static List <int> GenerateNumber1 ()
{
List <int> result = new List <int> (100 );
Random random = new Random ();
Int temp = 0;
While (result. Count <100)
{
Temp = random. Next (1, 34 );
If (! Result. Contains (temp ))
{
Result. Add (temp );
}
}
Return result;
}
Static List <int> GenerateNumber2 ()
{
List <int> container = new List <int> (33 );
List <int> result = new List <int> (6 );
Random random = new Random ();
For (int I = 1; I <= 33; I ++)
{
Container. Add (I );
}
Int index = 0;
Int value = 0;
For (int I = 1; I <= 6; I ++)
{
Index = random. Next (0, container. Count );
Value = container [index];
Result. Add (value );
Container. RemoveAt (index );
}
Return result;
}
Staticint [] GenerateNumber3 ()
{
// Store the 33 numbers from 1 to 33
Int [] container = newint [33];
// Save the returned results
Int [] result = newint [6];
Random random = new Random ();
For (int I = 0; I <33; I ++)
{
Container [I] = I + 1;
}
Int index = 0;
Int value = 0;
For (int I = 0; I <6; I ++)
{
// Obtain a random value from [1, container. Count + 1) to ensure that the value does not exceed the number of container elements
Index = random. Next (0, container. Length-I );
// Use the randomly generated value as the index to retrieve the value in the iner
Value = container [index];
// Place the randomly obtained value in the result set
Result [I] = value;
// Move the recently used container collection to the end
Container [index] = container [container. Length-I-1];
// Move the value of the queue to the queue
Container [container. Length-I-1] = value;
}
Return result;
}