Wednesday, October 10, 2012

Birthday Paradox Simulation in C

/* Given a group of n people how to calculate the probability that m people among them have the same birthday without using a formula*/


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

int main()
{
  int i, n, m, rand_birthday, j, a;
  int *array = NULL, c, k, t;
  float count = 0.0, trial = 1.0, prob, percent;
  
  printf("\nEnter the number of people in a room:");
  scanf("%d", &n);
  printf("\nEnter the number of people whose birthday ");
  printf("needs to be on the same day:");
  scanf("%d", &m);
  printf("\nEnter the no. of trials:");
  scanf("%d", &t);

  // Dynamically allocate memory for n elements
  array = (int *)calloc(n, sizeof(int));

  while(trial <= t)
  {
    for(i = 0; i < n; i++)
    {
      rand_birthday = gen_rand();
      array[i] = rand_birthday;
    }
    printf("\nRandom birthdays are : \n");
    for(i = 0; i < n; i++)
      printf(" %d ", array[i]);
    printf("\n");
  
    // Sorting the birthdays
    for(i = 0; i < n; i++)
    {
      for(j= i + 1; j < n; j++)
      {
        if(array[i] > array[j])
        {
          a = array[i];
          array[i] = array[j];
          array[j] = a;
        }
      }
    }

    printf("\nRandom birthdays(sorted) are : \n");
    for(i = 0; i < n; i++) 
      printf(" %d ", array[i]);
    printf("\n");

    // Check for the same birthdays
    i = 0; j = 1; 
    while(j < n)
    {
      c = 1;
      if(array[i] != array[j])
      {
        i++;
        j++;
      }
      else
      {
        for(k = j; ((k < n) && (array[i] == array[k])); k++)
          c++;
        i = k;
        j = k + 1;
        if(c >= m)
        {
          count++;
          break;
        }
      }
    }
    trial++;
  }

  // Calculate the probability
  printf("\ncount = %f, \ntrials = %f\n", count, trial);
  prob = (count/trial);
  printf("Probability of getting %d same birthdays", m);
  printf(" among %d people is %f", n, prob);
  percent = prob * 100;
  printf(" = %f percentage\n", percent);

  return 0;
}

int gen_rand(void)
/* returns random number in range of 0 to 364 */
{
   int n;
   n=rand() % 365;
   return(n);
}




Written by