Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you make a random number generator that chooses between the number 2 or 3. (not 1,2,3)

Tags:

c

random

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

like image 983
Shopimo Online Avatar asked Jan 27 '19 22:01

Shopimo Online


People also ask

How do you get the program to generate a random number between 1 and 10?

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

How do you generate a random number?

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


1 Answers

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;
like image 135
chqrlie Avatar answered Sep 18 '22 18:09

chqrlie