5

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

Bathsheba
  • 231,907
  • 34
  • 361
  • 483

3 Answers3

2

As @Kerrek SB suggest, your formula is: random() % 2 + 2:

  • random() % 2 ==> Gets [0 or 1]
  • [0 or 1] + 2 ==> Gets [2 or 3]

A functional code is:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>



int main()
{
    // Declare variables
    int i;
    int randomNumber;

    // Set random seed
    srand(time(NULL));

    // Get 10 random numbers between 2 and 3
    for (i = 0; i < 10; ++i){
        randomNumber = rand() % 2 + 2;
        printf("Random %d: %d\n", i, randomNumber);
    }

    // End function
    return 0;
}
JuMoGar
  • 1,740
  • 2
  • 19
  • 46
2

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;
chqrlie
  • 131,814
  • 10
  • 121
  • 189
2

This is not trivial using rand() since a linear congruential generator typically alternates between odd and even numbers.

So one of the worst things you can do it to use a formula based on rand() % 2.

In this particular case, I suggest you draw based on

n = rand();

and call it 1 if n < RAND_MAX / 2 and 3 otherwise, which you can do with

rand() < RAND_MAX / 2 ? 1 : 3

That might have adequate statistical properties - perhaps some unwanted autocorrelation - but probably no worse than rand() itself.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483