Reputation: 103
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.
Upvotes: 2
Views: 152
Reputation: 11228
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()));
Upvotes: 2
Reputation: 234715
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;
Upvotes: 6