How do I generate a random int number?

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

How do I generate a random integer in C#?

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

    I wanted to add a cryptographically secure version:

    RNGCryptoServiceProvider Class (MSDN or dotnetperls)

    It implements IDisposable.

    using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
    {
       byte[] randomNumber = new byte[4];//4 for int32
       rng.GetBytes(randomNumber);
       int value = BitConverter.ToInt32(randomNumber, 0);
    }
    
    0 讨论(0)
  • 2020-11-21 11:42

    I've tried all of these solutions excluding the COBOL answer... lol

    None of these solutions were good enough. I needed randoms in a fast for int loop and I was getting tons of duplicate values even in very wide ranges. After settling for kind of random results far too long I decided to finally tackle this problem once and for all.

    It's all about the seed.

    I create a random integer by parsing out the non-digits from Guid, then I use that to instantiate my Random class.

    public int GenerateRandom(int min, int max)
    {
        var seed = Convert.ToInt32(Regex.Match(Guid.NewGuid().ToString(), @"\d+").Value);
        return new Random(seed).Next(min, max);
    }
    

    Update: Seeding isn't necessary if you instantiate the Random class once. So it'd be best to create a static class and call a method off that.

    public static class IntUtil
    {
       private static Random random;
    
       private static void Init()
       {
          if (random == null) random = new Random();
       }
    
       public static int Random(int min, int max)
       {
          Init();
          return random.Next(min, max);
       }
    }
    

    Then you can use the static class like so..

    for(var i = 0; i < 1000; i++)
    {
       int randomNumber = IntUtil.Random(1,100);
       Console.WriteLine(randomNumber); 
    }
    

    I admit I like this approach better.

    0 讨论(0)
  • 2020-11-21 11:43
    Random r = new Random();
    int n = r.Next();
    
    0 讨论(0)
  • 2020-11-21 11:43

    create a Random object

    Random rand = new Random();
    

    and use it

    int randomNumber = rand.Next(min, max);
    

    you don't have to initialize new Random() every time you need a random number, initiate one Random then use it as many times as you need inside a loop or whatever

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

    I used below code to have a random number (not recommended):

    var random = new Random((int)DateTime.Now.Ticks);
    var randomValue = random.Next(startValue, endValue + 1);
    
    0 讨论(0)
  • 2020-11-21 11:43

    There are a number utility functions or services that are better cached in the same way that System.Random should be, so it lends itself to a generic implementation:

    static public class CachedService<T> where T : new() {
        static public T Get { get; } = new T();
    }
    

    To use for random (or similar):

    CachedService<System.Random>.Get.Next(999);
    
    0 讨论(0)
提交回复
热议问题