gpt4 book ai didi

c# - 包含最小值和最大值的 RNGCryptoServiceProvider

转载 作者:行者123 更新时间:2023-11-30 12:30:57 25 4
gpt4 key购买 nike

我需要一个方法,它返回从最小值到最大值的随机数,包括这两个数字。我在文章 .NET Matters: Tales from the CryptoRandom 中找到了一些代码来自 Stephen Toub 和 Shawn Farkas,该方法看起来像这样:

// Note - maxValue is excluded!
public static int GetRandomIntBetween(int minValue, int maxValue)
{
if (minValue > maxValue) throw new ArgumentOutOfRangeException("minValue");
if (minValue == maxValue) return minValue;

var rng = new RNGCryptoServiceProvider();
var uint32Buffer = new byte[4];
long diff = maxValue - minValue;

while (true)
{
rng.GetBytes(uint32Buffer);
uint rand = BitConverter.ToUInt32(uint32Buffer, 0);
const long max = (1 + (long)int.MaxValue);
long remainder = max % diff;
if (rand < max - remainder)
{
return (int)(minValue + (rand % diff));
}
}
}

我试图使 maxValue 包含在内:

public static int GetRandomIntBetween(int minValue, int maxValue)
{
if (minValue > maxValue) throw new ArgumentOutOfRangeException("minValue");
if (minValue == maxValue) return minValue;

// Make maxValue inclusive.
maxValue++;

var rng = new RNGCryptoServiceProvider();
var uint32Buffer = new byte[4];
long diff = maxValue - minValue;

while (true)
{
rng.GetBytes(uint32Buffer);
uint rand = BitConverter.ToUInt32(uint32Buffer, 0);
const long max = (1 + (long)int.MaxValue);
long remainder = max % diff;
if (rand < max - remainder)
{
return (int)(minValue + (rand % diff));
}
}
}

看起来很奇怪,但似乎我可以保持前两个检查不变,即使语义略有不同,它仍然有效。结果数据看起来也不错。我是不是漏掉了什么或者找零钱可以吗?

PS - 我问这个是因为生成随机数显然是一件非常微妙的事情,我想确保我的方法是正确的。

最佳答案

Look at my solution (click there)

您可以向类中添加其他方法:

public int NextInclusive(int minValue, int maxValue) {
return Next(minValue, maxValue + 1);
}

关于c# - 包含最小值和最大值的 RNGCryptoServiceProvider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14935708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com