Asif Mohammad
Asif Mohammad

Reputation: 69

Generate a random number from within a big range except a smaller range from the middle of the big range

This line of code generates a number from -9 to 9:

std::uniform_int_distribution<int> vDist(-9, 9);

However, what I want to do is generate a number from -9 to 9, except -3 to 3. I don't want the random number generator to give me a number within -3 to 3.

How can I write the code to exclude this inner range?

Upvotes: 0

Views: 93

Answers (2)

Tobias Ribizel
Tobias Ribizel

Reputation: 5421

Two possible solutions:

  • Rejection sampling:
    Retrieve a random number. If it's between -3 and 3, try again (do-while loop)
  • Mapping:
    Sample in a smaller interval like [-6, 5] and define a 1-to-1 mapping that maps this interval to
    [-9, -4] u [4, 9]:

    if (value < 0) value -= 3;
    else value += 4; // if (value >= 0)
    

Upvotes: 2

Phil Noderer
Phil Noderer

Reputation: 45

I'm not into c++, only c#, but the principle would work in every language.

you could just do a while Loop, generate a new number in each Iteration and check it with an if Statement, if it's greater than -3 and lower than 3. if so, proceed with the while Loop.

if not it has to be in your desired range and you can break the Loop and store your value.

Upvotes: 0

Related Questions