Alex Rivera | Logout

How can I generate a random number within a range but exclude some?

Asked 2011-06-22T16:17:39.097
46

How can I generate a random number within a range but exclude some, without keep generating and checking if the generated number is one of those that I want to exclude?

Edit
Report

1 Answer

2

Create a map that takes the output of a random function without the range restriction and map it to the range you want with restrictions.

For example, if I want a random int from 1-10 but never 7 I could do something like this:

int i = rand(1, 9);
if i>=7
  i++;
return i;

As long as you ensure that your mapping is 1:1, you can avoid skewing the randomness of your rand function.

answered 2011-06-22T16:20:04.097

Your Answer