How do I generate a random int number?

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

How do I generate a random integer in C#?

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

    Just as a note for future reference.

    If you're using .NET Core, multiple Random instances isn't as dangerous as before. I'm aware that this question is from 2010, but since this question is old but has some attraction, I think it's a good thing to document the change.

    You may refer to this question I made a while back:

    Did Microsoft change Random default seed?

    Basically, they have changed the default seed from Environment.TickCount to Guid.NewGuid().GetHashCode(), so if you create 2 instances of Random it won't display the same numbers.

    You can see the file diffs from .NET Framework/.NET Core (2.0.0+) here: https://github.com/dotnet/coreclr/pull/2192/commits/9f6a0b675e5ac0065a268554de49162c539ff66d

    It isn't as safe as RNGCryptoServiceProvider, but at least it won't give you weird results.

    0 讨论(0)
  • 2020-11-21 11:57

    For strong random seed I always use CryptoRNG and not Time.

    using System;
    using System.Security.Cryptography;
    
    public class Program
    {
        public static void Main()
        {
            var random = new Random(GetSeed());
            Console.WriteLine(random.Next());
        }
    
        public static int GetSeed() 
        {
            using (var rng = new RNGCryptoServiceProvider())
            {
                var intBytes = new byte[4];
                rng.GetBytes(intBytes);
                return BitConverter.ToInt32(intBytes, 0);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-21 11:57

    Use one instance of Random repeatedly

    // Somewhat better code...
    Random rng = new Random();
    for (int i = 0; i < 100; i++)
    {
        Console.WriteLine(GenerateDigit(rng));
    }
    ...
    static int GenerateDigit(Random rng)
    {
        // Assume there'd be more logic here really
        return rng.Next(10);
    }
    

    This article takes a look at why randomness causes so many problems, and how to address them. http://csharpindepth.com/Articles/Chapter12/Random.aspx

    0 讨论(0)
  • 2020-11-21 11:59

    Sorry, OP indeed requires a random int value, but for the simple purpose to share knowledge if you want a random BigInteger value you can use following statement:

    BigInteger randomVal = BigInteger.Abs(BigInteger.Parse(Guid.NewGuid().ToString().Replace("-",""), NumberStyles.AllowHexSpecifier));
    
    0 讨论(0)
  • 2020-11-21 12:01
    Random random = new Random ();
    int randomNumber = random.Next (lowerBound,upperBound);
    
    0 讨论(0)
  • 2020-11-21 12:01

    If you want a CSRNG to generate random numbers between a min and max, this is for you. It will initialize Random classes with secure random seeds.

        class SecureRandom : Random
        {
            public static byte[] GetBytes(ulong length)
            {
                RNGCryptoServiceProvider RNG = new RNGCryptoServiceProvider();
                byte[] bytes = new byte[length];
                RNG.GetBytes(bytes);
                RNG.Dispose();
                return bytes;
            }
            public SecureRandom() : base(BitConverter.ToInt32(GetBytes(4), 0))
            {
    
            }
            public int GetRandomInt(int min, int max)
            {
                int treashold = max - min;
                if(treashold != Math.Abs(treashold))
                {
                    throw new ArithmeticException("The minimum value can't exceed the maximum value!");
                }
                if (treashold == 0)
                {
                    throw new ArithmeticException("The minimum value can't be the same as the maximum value!");
                }
                return min + (Next() % treashold);
            }
            public static int GetRandomIntStatic(int min, int max)
            {
                int treashold = max - min;
                if (treashold != Math.Abs(treashold))
                {
                    throw new ArithmeticException("The minimum value can't exceed the maximum value!");
                }
                if(treashold == 0)
                {
                    throw new ArithmeticException("The minimum value can't be the same as the maximum value!");
                }
                return min + (BitConverter.ToInt32(GetBytes(4), 0) % treashold);
            }
        }
    
    0 讨论(0)
提交回复
热议问题