. Net true Random numbers

Source: Internet
Author: User
Tags random seed

Sad reminder, always remember how to write a true random number, the second time to turn the project notes, more sad to urge is that outside the project note can not be turned ...

Write a good copy here and share it with your friends who don't know.

Pseudo-random number related things are not written, God horse test, data, all omitted. All right, soft hearted, give a little.

Run once and know what a pseudo-random number is:

     for (int0; i++)    {      Console.WriteLine (new Random (). Next (1));    }

Casually pull two sentences: pseudo-random number is repeated because the random number method is the default time for random seed, and in programming, the time accuracy is limited, a short period of time to take time, this time value may be repeated,

The time (random number Seed) repeats, and the random number naturally repeats. So our solution is to provide a random number seed that never repeats.

On the code:

Get strong random number seed

        /// <summary>        ///Description: Create a cryptographically random number generator to generate a strong random seed/// </summary>        /// <returns></returns>        Static intgetrandomseed () {byte[] bytes =New byte[4]; System.Security.Cryptography.RNGCryptoServiceProvider rng=NewSystem.Security.Cryptography.RNGCryptoServiceProvider (); Rng.            GetBytes (bytes); returnBitconverter.toint32 (Bytes,0); }

How to use:

int New Random (Getrandomseed ()). Next (Nummin, Nummax);

PS: Method Two

Just said why would repeat, I suddenly thought, take the time as a random number of seeds, in a short time I do not let it take so many times, can not avoid repetition?

Try it:

             for (int0; i++)            {                Thread.Sleep (1); // force stop one millisecond                Console.WriteLine (New Random (). Next (1));            }

Sure enough not to repeat, I really witty ~ ~ * ^_^ *

. Net true Random numbers

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.