[英]generate random number not including some numbers
Is there a way to generate a random number from a group of numbers that wont include some numbers? 有没有办法从一组不包含某些数字的数字中生成一个随机数? For example - random number from 20-50 not including 25,27,34.
例如 - 20-50的随机数,不包括25,27,34。
A scheme where you generate a number in the range 20 to 50 then discard the ones you don't want will introduce statistical bias . 生成20到50范围内的数字然后丢弃不需要的数字的方案将引入统计偏差 。 (You'll tend to increase the variance of the resulting distribution; particularly if your generator is linear congruential).
(您将倾向于增加所得分布的方差;特别是如果您的生成器是线性同余的)。
The best way is to generate in the range 20 - 47 (call a drawing x
say) then make adjustments using 最好的方法是在20 - 47范围内生成(称为绘图
x
说)然后使用进行调整
if (x >= 25) ++x;
if (x >= 27) ++x;
if (x >= 34) ++x;
LINQ implementation of @Yeldar Kurmangaliyev comment: @Yeldar Kurmangaliyev的LINQ实施评论:
var allowed = Enumerable.Range(20, 31).Except(new int[] { 25, 27, 34 });
Random rand = new Random();
int randomNum = allowed.ElementAt(rand.Next(0, allowed.Count()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.