How do I generate a random int number?

前端 未结 30 2586
长发绾君心
长发绾君心 2020-11-21 11:02

How do I generate a random integer in C#?

相关标签:
30条回答
  • 2020-11-21 12:01

    I always have methods that generate random numbers which help for various purposes. I hope this may help you too:

    public class RandomGenerator  
    {  
        public int RandomNumber(int min, int max)  
        {  
            var random = new Random();  
            return random.Next(min, max);  
        }  
    
        public string RandomString(int size, bool lowerCase)  
        {  
            var builder = new StringBuilder();  
            var random  = new Random();  
            char ch;  
    
            for (int i = 0; i < size; i++)  
            {  
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));  
                builder.Append(ch);  
            }  
    
            if (lowerCase)  
                return builder.ToString().ToLower();  
            return builder.ToString();  
        }  
    }
    
    0 讨论(0)
  • Numbers calculated by a computer through a deterministic process, cannot, by definition, be random.

    If you want a genuine random numbers, the randomness comes from atmospheric noise or radioactive decay.

    You can try for example RANDOM.ORG (it reduces performance)

    0 讨论(0)
  • 2020-11-21 12:04

    You could use Jon Skeet's StaticRandom method inside the MiscUtil class library that he built for a pseudo-random number.

    using MiscUtil;
    ...
    
    for (int i = 0; i < 100; 
        Console.WriteLine(StaticRandom.Next());
    
    0 讨论(0)
  • 2020-11-21 12:04

    The easiest way is probably just Random.range(1, 3) This would generate a number between 1 and 2.

    0 讨论(0)
  • 2020-11-21 12:07

    Modified answer from here.

    If you have access to an Intel Secure Key compatible CPU, you can generate real random numbers and strings using these libraries: https://github.com/JebteK/RdRand and https://www.rdrand.com/

    Just download the latest version from here, include Jebtek.RdRand and add a using statement for it. Then, all you need to do is this:

    // Check to see if this is a compatible CPU
    bool isAvailable = RdRandom.GeneratorAvailable();
    
    // Generate 10 random characters
    string key       = RdRandom.GenerateKey(10);
    
     // Generate 64 random characters, useful for API keys 
    string apiKey    = RdRandom.GenerateAPIKey();
    
    // Generate an array of 10 random bytes
    byte[] b         = RdRandom.GenerateBytes(10);
    
    // Generate a random unsigned int
    uint i           = RdRandom.GenerateUnsignedInt();
    

    If you don't have a compatible CPU to execute the code on, just use the RESTful services at rdrand.com. With the RdRandom wrapper library included in your project, you would just need to do this (you get 1000 free calls when you signup):

    string ret = Randomizer.GenerateKey(<length>, "<key>");
    uint ret   = Randomizer.GenerateUInt("<key>");
    byte[] ret = Randomizer.GenerateBytes(<length>, "<key>");
    
    0 讨论(0)
  • 2020-11-21 12:08

    I wanted to demonstrate what happens when a new random generator is used every time. Suppose you have two methods or two classes each requiring a random number. And naively you code them like:

    public class A
    {
        public A()
        {
            var rnd=new Random();
            ID=rnd.Next();
        }
        public int ID { get; private set; }
    }
    public class B
    {
        public B()
        {
            var rnd=new Random();
            ID=rnd.Next();
        }
        public int ID { get; private set; }
    }
    

    Do you think you will get two different IDs? NOPE

    class Program
    {
        static void Main(string[] args)
        {
            A a=new A();
            B b=new B();
    
            int ida=a.ID, idb=b.ID;
            // ida = 1452879101
            // idb = 1452879101
        }
    }
    

    The solution is to always use a single static random generator. Like this:

    public static class Utils
    {
        public static readonly Random random=new Random();
    }
    
    public class A
    {
        public A()
        {
            ID=Utils.random.Next();
        }
        public int ID { get; private set; }
    }
    public class B
    {
        public B()
        {
            ID=Utils.random.Next();
        }
        public int ID { get; private set; }
    }
    
    0 讨论(0)
提交回复
热议问题