static System.Security.Cryptography.RandomNumberGenerator RandomNumberGenerator = null;
/// <summary>
/// 回傳大於等於 0 小於 1
/// </summary>
/// <returns></returns>
public static double NextDouble()
{
if (RandomNumberGenerator == null || LastRandomGenerateTime < DateTime.Now.AddMinutes(-1))
{
RandomNumberGenerator = System.Security.Cryptography.RandomNumberGenerator.Create();
}
// Generate four random bytes
byte[] four_bytes = new byte[4];
RandomNumberGenerator.GetBytes(four_bytes);
// Convert the bytes to a UInt32
uint scale = BitConverter.ToUInt32(four_bytes, 0);
// And use that to pick a random number >= min and < max
// 0 <= (scale / (uint.MaxValue + 1.0)) < 1
return scale / (uint.MaxValue + 1.0);
}
/// <summary>
/// 回傳值介於 min ~ (max - 1)
/// </summary>
/// <param name="min"></param>
/// <param name="max"></param>
/// <returns></returns>
public static int GetRandomInt(int min, int max)
{
if(max < min)
{
throw new Exception("最大值不可小於最小值");
}
// Generate four random bytes
byte[] four_bytes = new byte[4];
RandomNumberGenerator.GetBytes(four_bytes);
// And use that to pick a random number >= min and < max
return (int)(min + (max - min) * NextDouble()); //因為 NextDouble 會小於 1,所以用無條件捨去.
}
/// <summary>
/// 產生 0 ~ (max - 1) 的亂數
/// </summary>
/// <param name="max"></param>
/// <returns></returns>
public static int GetRandomInt(int max)
{
return GetRandomInt(0, max);
}
/// <summary>
/// 產生 0 ~ (int.MaxValue - 1) 的亂數
/// </summary>
/// <returns></returns>
public static int GetRandomInt()
{
return GetRandomInt(int.MaxValue);
}