How do I generate a random int number?

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

How do I generate a random integer in C#?

30条回答
  •  自闭症患者
    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.

提交回复
热议问题