【发布时间】:2019-11-27 20:34:39
【问题描述】:
上下文:我正在构建一个随机数生成用户界面,用户可以在其中输入以下值:
- lowerLimit:每个随机生成数的下限
- upperLimit:每个随机生成数字的上限
- maxPrecision:每个随机生成数的最大精度
- 数量:要生成的随机数值的最大数量
问题是:如何确保在给定的下限/上限范围和给定精度下,用户不会请求比可能更大的数量?
例子:
下限:1 上限:1.01 最大精度:3 数量:50
在此精度级别 (3) 上,1 和 1.01 之间有 11 个可能的值:1.000、1.001、1.002、1.003、1.004、1.005、1.006、1.007、1.008、1.009、1.100,但用户要求前 50 名。
在一个只返回符合用户条件的不同值的函数版本中,我使用字典对象来存储已经生成的值,如果该值已经存在,请尝试另一个随机数,直到找到 X 个不同的随机数其中 X 是用户所需数量的值。问题是,如果可能值的数量少于用户输入的数量,我的逻辑允许一个永无止境的循环。
虽然我可能会使用逻辑来检测失控情况,但我认为提前以某种方式计算可能返回值的数量以确保它是可能的会是一种更好的方法。但这种逻辑让我难以理解。 (什么都没试过,因为我想不出怎么做)。
请注意:我确实看到了问题 Generating random, unique values C#,但没有解决我的问题的具体细节,即在给定精度和随后的失控条件下可能值的数量。
private Random RandomSeed = new Random();
public double GetRandomDouble(double lowerBounds, double upperBounds, int maxPrecision)
{
//Return a randomly-generated double between lowerBounds and upperBounds
//with maximum precision of maxPrecision
double x = (RandomSeed.NextDouble() * ((upperBounds - lowerBounds))) + lowerBounds;
return Math.Round(x, maxPrecision);
}
public double[] GetRandomDoublesUnique(double lowerBounds, double upperBounds, int maxPrecision, int quantity)
{
//This method returns an array of doubles containing randomly-generated numbers
//between user-entered lowerBounds and upperBounds with a maximum precision of
//maxPrecision. The array size is capped at user-entered quantity.
//Create Dictionary to store number values already generated so we can ensure
//we don't have duplicates
Dictionary<double, int> myDoubles = new Dictionary<double, int>();
double[] returnValues = new double[quantity];
double nextValue;
for (int i = 0; i < quantity; i++)
{
nextValue = GetRandomDouble(lowerBounds, upperBounds, maxPrecision);
if (!myDoubles.ContainsKey(nextValue))
{
myDoubles.Add(nextValue, i);
returnValues[i] = nextValue;
}
else
{
i -= 1;
}
}
return returnValues;
}
【问题讨论】:
-
任意数量的随机数在任意范围内和任意精度都是可能的,因为根据定义,随机数是允许重复出现的。如果您说您永远不想重复出现相同的数字,那么您正在寻找shuffle,而不是随机数。
标签: c# random distinct precision