如何在C#中生成随机整数?


当前回答

除了COBOL答案,我已经尝试了所有这些解决方案。。。英雄联盟

这些解决方案都不够好。我需要一个快速的for int循环中的随机数,即使在很宽的范围内,我也得到了大量的重复值。在接受了太长时间的随机结果之后,我决定最终彻底解决这个问题。

这都是关于种子的。

我通过解析Guid中的非数字来创建一个随机整数,然后使用它来实例化random类。

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);
}

更新:如果实例化Random类一次,则无需种子化。所以最好创建一个静态类并调用一个方法。

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);
   }
}

然后您可以像这样使用静态类。。

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

我承认我更喜欢这种方法。

其他回答

如其他答案中所述,一个好的安全方法是使用安全密码生成器。这里的所有示例都显示了RNGCryptoServiceProvider的用法,与我建议的解决方案相比,它编写的代码很长。

使用RandomNumberGenerator,它是在密码学API之上编写的。它和RNGCryptoServiceProvider一样安全,并且具有相同的随机性。

// Gives a random number for the integer range.
// You can simply update the parameters as your needs.
RandomNumberGenerator.GetInt32(int.MinValue, int.MaxValue);

每次执行新的Random()时,它都会初始化。这意味着在一个紧密的循环中,你会多次获得相同的值。您应该保留一个Random实例,并在同一实例上继续使用Next。

//Function to get random number
private static readonly Random getrandom = new Random();

public static int GetRandomNumber(int min, int max)
{
    lock(getrandom) // synchronize
    {
        return getrandom.Next(min, max);
    }
}

抱歉,OP确实需要一个随机整型值,但为了分享知识,如果您想要一个随机BigInteger值,可以使用以下语句:

BigInteger randomVal = BigInteger.Abs(BigInteger.Parse(Guid.NewGuid().ToString().Replace("-",""), NumberStyles.AllowHexSpecifier));

有许多实用程序函数或服务以与System.Random相同的方式更好地缓存,因此它适合于通用实现:

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

用于随机(或类似):

CachedService<System.Random>.Get.Next(999);

为什么不使用int randomNumber=Random.Range(start_Range,end_Range)?