If you are using Random.Range()
to generate values, is there any way to exclude some values within the range (for example: pick a number between 1 and 20, but not 6 through 8)?
Range() Really Maximally Inclusive? According to the C# documentation, "Returns a random float number between and min [inclusive] and max [inclusive]." However, after running a few tests, it appears as though the max is actually exclusive.
Use randrnage() to generate random integer within a range Use a random. randrange() function to get a random integer number from the given exclusive range by specifying the increment. For example, random. randrange(0, 10, 2) will return any random number between 0 and 20 (like 0, 2, 4, 6, 8).
The best way to do this is to use your favourite generator to generate an integer n
between 1 and 17 then transform using
if (n > 5){
n += 3;
}
If you sample between 1 and 20 then discard values you can introduce statistical anomalies, particularly with low discrepancy sequences.
So you actually want 17
(20 - 3) different values
[1..5] U [9..20]
and you can implement something like this:
// Simplest, not thread-safe
private static Random random = new Random();
...
int r = (r = random.Next(1, 17)) > 5
? r + 3
: r;
In general (and complicated) case I suggest generating an array of all possible values and then take the item from it:
int[] values = Enumerable
.Range(1, 100) // [1..100], but
.Where(item => item % 2 == 1) // Odd values only
.Where(item => !(item >= 5 && item <= 15)) // with [5..15] range excluded
//TODO: Add as many conditions via .Where(item => ...) as you want
.ToArray();
...
int r = values[random.Next(values.Length)];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With