rraanndd() -- General Function (libc)

Generate pseudo-random numbers
#iinncclluuddee <ssttddlliibb.hh>
iinntt rraanndd()

rraanndd() generates  a set of  pseudo-random numbers.  It  returns integers in
the range 0  to 32,767, and purportedly has a  period of 2^32.  rraanndd() will
always return the  same series of random numbers unless  you first call the
function ssrraanndd() to change rraanndd()'s _s_e_e_d, or beginning-point.

_E_x_a_m_p_l_e
The following  example uses rraanndd()  to implement the ``Let's  Make a Deal''
game  of  probability  described  by  Massimo  Piattelli-Palmarini  in  the
March/April  1991 issue  of _B_o_s_t_o_n_i_a magazine.   In brief,  an investigator
places a  dollar bill into one  of three boxes.  A  subject enters the room
and guesses which  box holds the bill.  The investigator  then opens one of
the  two unselected  boxes (one  that  is always  empty), shows  it to  the
subject, then offers the subject a choice: either stand pat with the box he
has  selected,  or switch  to  the  other non-selected  box.   The laws  of
probability state that the subject should always switch from the box he has
selected; this example tests that hypothesis.

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

main()
{
    int box[3], win, i, j;

    srand(time(NULL));

    /* Test 1:  the subject always stands pat.  For the sake of simplicity,
     * the subject always chooses box 0. */
    for (i = 0, win = 0; i < 1500; i++) {
        for (j = 0; j < 3; j++)
            box[j] = 0;

        box[rand()%3]++;

        if (box[0])
            win++;
    }
    printf("Test 1, always stand pat:  1500 iterations, %d winners\n", win);

    /* Test 2:  the subject always switches boxes. */
    for (i = 0, win = 0; i < 1500; i++) {
        for (j = 0; j < 3; j++)
            box[j] = 0;

        box[rand()%3]++;

        /* if box 2 is empty, pick box 1 */
        if (!box[2])
            win += box[1];
        else
            win += box[2];
    }
    printf("Test 2, always switch:  1500 iterations, %d winners\n", win);

    /* Test 3:  the subject switches boxes randomly. */
    for (i = 0, win = 0; i < 1500; i++) {
        for (j = 0; j < 3; j++)
            box[j] = 0;

        box[rand()%3]++;

        /* if box 2 is empty, pick box 1 */
        if (!box[2]) {
            if (rand()%2)
                win += box[1];
            else
                win += box[0];
        } else {
            if (rand()%2)
                win += box[2];
            else
                win += box[0];
        }
    }
    printf("Test 3, randomly switch:  1500 iterations, %d winners\n", win);
}

_S_e_e _A_l_s_o
lliibbcc, RRAANNDD_MMAAXX, ssrraanndd(), ssttddlliibb.hh
_T_h_e _A_r_t _o_f _C_o_m_p_u_t_e_r _P_r_o_g_r_a_m_m_i_n_g, vol. 2
ANSI Standard, section 7.10.2.1
POSIX Standard, section 8.1
