Several methods for asp.net to generate random numbers

Source: Internet
Author: User
Tags current time rand random seed

We can initialize a random number generator in two ways:

?? The first method does not specify the random seed. The system automatically selects the current time as the random seed:

?? Random ro = new Random ();
Instance

Private static char [] constant = {'0', '1', '2', '3', '4', '5', '6', '7 ', '8', '9', 'A', 'B', 'C', 'D', 'e', 'F', 'G', 'H ', 'I', 'J', 'K', 'L', 'M', 'n', 'O', 'P', 'Q', 'R ','s ', 'T', 'u', 'V', 'W', 'X', 'y', 'z', 'A',' B ', 'C', 'D', 'e', 'F', 'G', 'H', 'I', 'J', 'K', 'L ', 'M', 'n', 'O', 'P', 'Q', 'R', 'S', 'T', 'u', 'V ', 'W', 'X', 'y', 'Z '};

Public string pxkt_GetCharFont (int strLength)
{
System. Text. StringBuilder newRandom = new System. Text. StringBuilder (62 );
Random rd = new Random ();
For (int I = 0; I <strLength; I ++)
{
NewRandom. Append (constant [rd. Next (62)]);
}
Return newRandom. ToString ();
}

?? The second method can specify an int type parameter as a random seed:


?? Int iSeed = 10;

?? Random ro = new Random (10 );

?? Then, we can use this random class object to generate a random number. At this time, we need to use the random. next () method. This method is quite flexible. You can even specify the upper and lower limits of the generated random number.


Instance

/// <Summary>
/// Generate a random number of specified digits
/// </Summary>
/// <Param name = "VcodeNum"> Number of digits generated </param>
/// <Returns> </returns>
Private string RndNum (int VcodeNum)
{
String Vchar = ";
Vchar = Vchar + ", A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, r, S, T, U, V, W, X, Y, Z ";
Vchar = Vchar. ToLower ();
String [] VcArray = Vchar. Split (',');
String VNum = ""; // StringBuilder is not required because the string is short.
Int temp =-1; // record the previous random value. Avoid producing several identical random numbers.

// Use a simple algorithm to ensure different random numbers are generated
Random rand = new Random ();
For (int I = 1; I <VcodeNum + 1; I ++)
{
If (temp! =-1)
{
Rand = new Random (I * temp * unchecked (int) DateTime. Now. Ticks ));
}
Int t = rand. Next (35 );
If (temp! =-1 & temp = t)
{
Return RndNum (VcodeNum );
}
Temp = t;
VNum + = VcArray [t];

}
Return VNum;
}

2. Define a method to draw the verification code.

/// <Summary>
/// Create a verification code for the specified array
/// </Summary>
/// <Param name = "checkCode"> verification code </param>
Private void CreateImage (string checkCode)
{
Int iwidth = (int) (checkCode. Length * 15 );
System. Drawing. Bitmap image = new System. Drawing. Bitmap (iwidth, 25 );
Graphics g = Graphics. FromImage (image );
G. Clear (Color. White );
// Define the color
Color [] c = {Color. Black, Color. Red, Color. DarkBlue, Color. Green, Color. Brown, Color. DarkCyan, Color. Purple, Color. YellowGreen };
// Define the font
String [] font = {"Times New Roman", "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", ""};
Random rand = new Random ();
// Random output noise
For (int I = 0; I <50; I ++)
{
Int x = rand. Next (image. Width );
Int y = rand. Next (image. Height );
// G. DrawRectangle (new Pen (Color. LightGray, 0), x, y, 1, 1 );
G. DrawLine (new Pen (Color. LightPink, 0), x, y, 50, 23 );
}

// Output verification code characters of different fonts and colors
For (int I = 0; I <checkCode. Length; I ++)
{
Int cindex = rand. Next (7); // random from 7 colors
Int findex = rand. Next (6); // random from 6 fonts

Font f = new System. Drawing. Font (font [findex], 13, System. Drawing. FontStyle. Regular );
Brush B = new System. Drawing. SolidBrush (c [cindex]);
Int ii = 4;
// When an even number is used, the generated character width is 4 and the odd number is 2.
If (I + 1) % 2 = 0)
{
Ii = 2;
}
G. DrawString (checkCode. Substring (I, 1), f, B, 3 + (I * 12), ii );
}
// Draw a border
G. DrawRectangle (new Pen (Color. Black, 0), 0, 0, image. Width-1, image. Height-1 );

// Output to the browser
System. IO. MemoryStream MS = new System. IO. MemoryStream ();
Image. Save (MS, System. Drawing. Imaging. ImageFormat. Jpeg );
Response. ClearContent ();
Response. ContentType = "image/Jpeg ";
Response. BinaryWrite (ms. ToArray ());
G. Dispose ();
Image. Dispose ();
}

3. Test in the page_load event

Protected void Page_Load (object sender, EventArgs e)
{

If (! Page. IsPostBack)
{
String Code = this. RndNum (4 );
Session ["Code"] = Code;
This. CreateImage (Code );
}
}

Summary

Use the default time-related seed value to initialize a new instance of the Random class.

[Visual Basic] Public Sub New ()
[C #] public Random ();
[C ++] public: Random ();
[JScript] public function Random ();
Use the specified seed value to initialize a new instance of the Random class.

[Visual Basic] Public Sub New (Integer)
[C #] public Random (int );
[C ++] public: Random (int );
[JScript] public function Random (int );


Next has been overloaded. Returns a random number.
NextBytes uses a random number to fill in the elements of the specified byte array.
NextDouble returns a random number between 0.0 and 1.0.

Related Article

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.