Search code examples
crandomposixprobabilityansi-c

How to define rand() according to probability?


I have one bag with three equal balls. I made code to simulate the number of times each ball comes off (it works flawlessly so far).

Code

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <string.h>

#define N 50 /* Number of simulations*/
#define P 3  /* Number of of balls*/

unsigned long long millitime2(){
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return (unsigned long long)(tv.tv_usec);
}

int main() {
    int i;
    int num = 0;
    int *v;
    if((v = malloc(N*sizeof(int))) == NULL){
        printf("\n\tMEMORY ERROR");
        exit(1);
    }
    memset(v,0,N);
    printf("\nexpected freq: %f\n\n", ((float)1/(float)P)*100);

    for (i=0; i<N; i++){
        srand(millitime2());
        num = (rand()%P);
        v[num]++;
    }
    for(i=0;i<P;i++){
        printf("ball:%d   picked:%d/%d   freq:%f\n",i+1,v[i],N,((float)v[i]/(float)N)*100);
    }
    printf("\n");
    return 0;
}

But now the study I'm doing requires that from three balls; one ball is blue and two balls are white.

What do I have to change in the line with rand(), so it spits a blue ball one out of three times (~33%) and a white ball two out of three times(~66%)?


Solution

  • int x = rand() % 3;
    

    x will choose a 'random' number between 0 and 2

    if x <= 1 then white ( 66%) if x == 2 then blue ( 33%)