Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude values from Random.Range()?

Tags:

c#

random

unity3d

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)?

like image 272
Dinovr Avatar asked Jun 17 '16 10:06

Dinovr


People also ask

Is random range exclusive?

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.

How do you create a random range?

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).


2 Answers

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.

like image 160
Bathsheba Avatar answered Sep 28 '22 00:09

Bathsheba


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)];
like image 43
Dmitry Bychenko Avatar answered Sep 28 '22 00:09

Dmitry Bychenko