Question

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%)?

Was it helpful?

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

OTHER TIPS

make your own function

#define BLUE 1
#define WHITE 2

int whichBall()
{
  int val = rand() % P;
  if (val == 0)
    return BLUE;
  return WHITE;
}

this will return BLUE 33% of the time and WHITE 66% of the time

for 10 balls 3 blue 3 white and 4 black do:

#define BLUE = 3
#define WHITE = 3
#define BLACK = 4

int whichBall()
{
  int val = rand() % P;
  if (val < BLUE)
    return BLUE;
  if (val < BLUE + WHITE)
    return WHITE;
  if (val < BLUE + WHITE + BLACK)
    return BLACK
  return BLACK;//This line should never be reached but is included so it compiles
}

One workaround for this is:

  • Imagine having a bag with 10 balls, 3 red, 3 blue, 3 green, and 1 white.

  • Get an array[10].

  • Fill [0][1][2] with 'red', [3][4][5] with 'blue', [6][7][8] with 'green' and [9] 'white'.

  • Call rand()%10 = index of array.

  • You will get approximately 30% red, 30% blue, 30% green and 10% white.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top