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.
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 . (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
if (x >= 25) ++x;
if (x >= 27) ++x;
if (x >= 34) ++x;
LINQ implementation of @Yeldar Kurmangaliyev comment:
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()));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.