#include <stdlib.h>

int main(int argc, char *argv[])
{
  double sum_w1, sum_w2;
  int i, num_samples;

  num_samples = atoi(argv[1]);

  /* Seed the random-number generator with current time so that
   * the numbers will be different every time we run.
   */
  srand( (unsigned)time( NULL ) );

  /* Likelihood weighting part. */
  sum_w1 = sum_w2 = 0;

  for (i=0; i<num_samples; i++) {
    double weight;
    int a, b;

    weight = 1.0;
    a = coin_toss(0.2);
    b = (a==0)?coin_toss(0.6):coin_toss(0.7);

    if (b==0) weight *= 0.4;
    else weight *= 0.1;

    if (a==1)  sum_w1 += weight;
    sum_w2 += weight;
  }

  /* Display result. */  
  printf("Prob(A|B)=%g\n", sum_w1/sum_w2);
}

/* Returns 1 with probability p. If it doesn't return 1, returns 0. */
int coin_toss(double p)
{
  double t = (double)rand() / RAND_MAX;
  return (t>p)?0:1;
}

