Hi I am working on a monty hall generator and in part of my code I need it to generate random number 2 or 3. It cannot be 1,2,3 but the computer needs to select between 2 or 3. Thanks!
I have tried randomCarDoor = ( rand() % 3 ) + 1;
but does not work.
randomCarDoor = ( rand() % 3 ) + 1;
It gives me the number 1,2,3
but I just want 2
and 3
For example, to generate a random number between 1 and 10, we can do it like below. ThreadLocalRandom random = ThreadLocalRandom. current(); int rand = random. nextInt(1, 11);
There are two main methods that a computer generates a random number: true random number generators (TRNGs) and pseudo-random number generators (PRNGs). The former uses some phenomenon outside the computer for its number generation, whereas the latter relies on pre-set algorithms to emulate randomness².
You can use the low order bit of the random value, but it is very risky as some pseudo-random number generators do not provide adequate dispersion on low order bits:
int two_or_three = 2 + rand() % 2;
A much better way is to use the magnitude of the random number which is specified as having a flat distribution:
int two_or_three = 2 + (rand() >= RAND_MAX / 2);
If you want numbers 1
and 3
, here is a simple solution for any pair:
int random_value = (rand() < RAND_MAX / 2) ? 1 : 3;
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